+ 1
C++ ticket office question 35
Hi everyone, I have a question regarding arithmetic with variables of different data types. Why does my code only works if "min" was declared as a "double" and not "int"? I would wrongly get the first value of whatever is in the arithmetic statement of price. ( in this case, it is 50 instead of 44.5) #include <iostream> using namespace std; int main() { int ages[5]; for (int i = 0; i < 5; ++i) { cin >> ages[i]; } //your code goes here double min = 200; //why does this not work? //int min = 200; double price; for (int i=0; i<5; i++){ if(min>ages[i]){ min = ages[i]; } } price = (50-(50*(min/100))); cout<<price; return 0; }
3 Respostas
+ 2
int/int results int type only..
At least one as int/double or double/int or double/double results double value..
So in
price = (50-(50*(min/100)));
min/100 both int and if min is less than 100 then min/100 = 0 so finally it's 50-0= 50
5/2= 2 (2.5 converted back to int so 2 is results
But 5.0/2= 2.5 , all values casted to bigger type first to not loss any data..
hope it helps..
+ 1
I understand it now with your explanation. Thank you very much.
0
You're welcome..