Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ type converting issue

Tags:

c++

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;

like image 517
user2534633 Avatar asked Jun 29 '13 13:06

user2534633


People also ask

Which type of conversion is not acceptable in C?

Which type of conversion is NOT accepted? Explanation: Conversion of a float to pointer type is not allowed.

Is type conversion possible in C?

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.

How the type conversions are handled by C?

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.

How many types of conversions are there in C?

There are two types of conversion: implicit and explicit. The term for implicit type conversion is coercion.


1 Answers

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.

like image 106
Joni Avatar answered Oct 21 '22 15:10

Joni