954,504 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

rounded number problem

in this program i'm writing, i seem to keep getting rounded down values. At first i though it was because i was declaring my return variable as an integer so i made sure i wasnt doing that and changed all number variables in the class to doubles to ensure i wasnt going wrong there and still i divide 3 into 4 and get 0.

double fraction::percent()
{
  double _percent=_top/_bottom*100+(_whole*100);
   cout<<_bottom<<endl<<endl<<"percent "<<3/4/**100+(_whole*100)*/<<endl;
 return(_percent);
}


the calculation was 3/4*100+_whole*100, i commented out all but the first part to see what 3/4 returns and i get 0 instead of .75.

James19142
Newbie Poster
18 posts since Oct 2009
Reputation Points: 6
Solved Threads: 0
 

1) Don't create variables with _ as the first character. That's used for internal values
2) top, bottom, whole are probably integers.

WaltP
Posting Sage w/ dash of thyme
Moderator
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

The issue is integer division vs. floating-point division.

Integer division divides an integer divisor into an integer dividend and produces an integer quotient. For example, if you have 11/3, integer division will produce a truncated integer result of 3 instead of the actual correct value of 3.6667, which is a floating-point value.

In your code, you have this:

3/4 /**100+(_whole*100)*/ << endl;

notice how the 3 and the 4 do not have decimal points. This causes C++ to interpret them as integers, which results inint / int. This combination results in integer division.

Can you think of a way to change this code so that it results in double / double which will give you floating-point division instead?

Fbody
Posting Maven
2,930 posts since Oct 2009
Reputation Points: 833
Solved Threads: 393
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: