-3

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 :)

ST3
  • 8,826
  • 3
  • 68
  • 92
  • I dont know why people is answering that question, instead of saying that it is a duplicate, or helping with a comment, or saying that "does not show any research effort, it is unclear, or NOT USEFUL"... – sebas Mar 11 '14 at 22:50
  • 1
    @sebas it faster to answer, then found a dup, but agree about no research. – ST3 Mar 11 '14 at 22:54
  • Sorry @ST3, you are right. I agree with you that it is faster. It is just that there are too many question without any research effort. I am a bit upset with that... – sebas Mar 11 '14 at 23:02

3 Answers3

2

You need to divide by 100.0 rather than 100

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
2

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.

ST3
  • 8,826
  • 3
  • 68
  • 92
0

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.

user38457
  • 21
  • 3