Question

Helo, I'm new to programming and run into an issue, I have an integer, for example 158, and I divide it by 100 that i get is 1, but I want 1.58 instead

It is probably known issue, but sorry, I'm noob, for now :)

Was it helpful?

Solution

Just cast this to float number

int i = 158;
float f = (float)i / 100;  //less precision
double d = (double)i / 100;  //more precision
//other way
int i = 158;
float f = i / 100.0;  //less precision
double d = i / 100.0;  //more precision

What you are doing is dividing integer from integer, in this case result always integer, to get floating point number at least one of two operand has to be floating point number.

OTHER TIPS

You need to divide by 100.0 rather than 100

Dividing by an integer in C++ is always going to give you an integer, so it will never be completely accurate. That being said, it was mentioned above that you can divide by a double or long to get the accurate decimal number that you desire.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top