A simple problem. DOUBLE TROUBLE

Started by
2 comments, last by Marz 19 years, 2 months ago
I can't figure out why this returns 0. I would greatly appreciate help. Thank you.



#include <iostream>

using namespace std;

int main() {
double fin;




fin = (87/100)* 50;

cout << "\n\t" << fin <<"\n\n\n";

system("PAUSE");
return 0;
}


Advertisement
(87/100) = 0

thats integer division

(87.0f/100.0f) would work however

hope that helps
-Dan
When General Patton died after World War 2 he went to the gates of Heaven to talk to St. Peter. The first thing he asked is if there were any Marines in heaven. St. Peter told him no, Marines are too rowdy for heaven. He then asked why Patton wanted to know. Patton told him he was sick of the Marines overshadowing the Army because they did more with less and were all hard-core sons of bitches. St. Peter reassured him there were no Marines so Patton went into Heaven. As he was checking out his new home he rounded a corner and saw someone in Marine Dress Blues. He ran back to St. Peter and yelled "You lied to me! There are Marines in heaven!" St. Peter said "Who him? That's just God. He wishes he were a Marine."
The type of the variable to which an expression is assigned doesn't affect the way in which the expression is evaluated; it just gets converted at the end.

Therefore, the math is being done with integers. Thus the first operation is an integer division, which results in an integer and discards the remainder. Thus 87/100 yields 0, with a (discarded) remainder of 87. 0 times 50 is still 0. Assigning integer 0 to a double variable requires conversion, but the value is still 0.
Yup I understand now. Thank you. Man I wish it would just do the conversions. This is going to cause the function that I pulled this from problems as it takes int as arguments from another function. Oh well I'll get it now somehow.

Thanks again folks.

This topic is closed to new replies.

Advertisement