Consider following code:
#include <iostream>
using namespace std;
int aaa(int a) {
cout << a * 0.3 << endl;
return a * 0.3;
}
int main()
{
cout << aaa(35000);
}
It prints out:
10500
10499
Why output differs?
I have a workaround to use "return a * 3 / 10;" but I don't like it.
Edit:
Found that doing "return float(a * 0.3);" gives expected value;
Which type of conversion is NOT accepted? Explanation: Conversion of a float to pointer type is not allowed.
Typecasting is a method in C language of converting one data type to another. There are two types of typecasting. 1. Implicit Type casting − This conversion is done by the compiler.
Implicit Type Conversion In C Notice that we have assigned the double value to an integer variable. int number = value; Here, the C compiler automatically converts the double value 4150.12 to integer value 4150. Since the conversion is happening automatically, this type of conversion is called implicit type conversion.
There are two types of conversion: implicit and explicit. The term for implicit type conversion is coercion.
The result of 0.3*35000 is a floating point number, just slightly less than 10500. When printed it is rounded to 10500, but when coerced into an int the fractional digits are discarded, resulting in 10499.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With