+ 1
What is the difference?
#include <iostream> using namespace std; int main() { int a = 30; int b = 12; float c = a / b; cout << c; return 0; } The output is 2 But if I exchange one(or just two) of the data types of a and b into float, I get an output 2.5. What is the difference? I mean that I have already declared c is an float, why the data type of a and b change the result. Thanks.
6 odpowiedzi
+ 6
Result of a/b results integer value because a and b are defined an integer.
To get float value as result of a/b, you can typecast the result to float as-
float c=(float)(a/b);
+ 6
Sorry, mistakenly I put extra parenthesis,
You have to typecast atleast one integer variable as float to get the floating pt number.
eg.
float c=(float)a/b;
+ 2
When you divide two integers, you are performing integer division, so only the integer part of the calculation is retained, and the decimal part is discarded.
+ 1
I don't know C++, but I do know that in some languages when the / operator takes two ints as arguments, it does an integer division (that is, returns an integer). For example, if you do float c=a/(float)b it returns the expected result.
0
@Sachin If you do that, you are still making an integer division because you are passing two integers to the / operator, so it doesn't change the output.
0
Thank you for all the answers. I got it.☺