-5

I am coding a very simple program in C but I keep getting wrong answers to calculations that I am doing. The final output that I want needs to have no decimal places so I am using int as the data type even though the answer will not be an integer. Here is the code:

int numberOfInches = (100/254)*101;

I either get the answer 0 if I use int as the data type or crazy long numbers if I try using float or double. Any ideas on what I am doing wrong?

Mathieu
  • 8,840
  • 7
  • 32
  • 45
A-Lill
  • 1
  • 6

6 Answers6

5
100 / 254

This is integer division, which will get 0. You then multiply by 101.

To do floating point division, at least one of the operands of / must be floating point:

int n = (int)((100. / 254.) * 101.);
Bo Persson
  • 90,663
  • 31
  • 146
  • 203
bolov
  • 72,283
  • 15
  • 145
  • 224
1

Obviously it will give 0.

int numberOfInches = (100/254)*101;

When it will calculated first it will evaluate inner bracket. so (100/254) will be 0 And when you multiply 0 to 101, i.e 0*101 = 0.

It will be 0.

To get the correct output, use the following.

int numberOfInches =(int)((100.0/254)*101);
Pirate
  • 2,886
  • 4
  • 24
  • 42
1

When both operands of the / operator are integer, it performs integer division, i.e. the result is the quotient with the fraction part trucated. The result of 100/254 is less that 1, so it rounds down to 0.

You can either make one of the constants floating point:

(100.0/254)*101

Or you can do the division last:

(100*101)/254
dbush
  • 205,898
  • 23
  • 218
  • 273
1

You use an int. The results are rounded to the nearest int value:

100/254 = 0 THEN 0 * 101 = 0 SO, final result is 0.

I think you can do something like :

int numberOfInches = 100 * 101 / 254;

result: 100 * 101 = 10100 THEN 10100 / 254 = 39.7xxxxxx SO, final result is 40.

Victor Castro
  • 1,232
  • 21
  • 40
1

Division in parentheses is integer-type, so 100/254=0. If you want to calculate value with a fractional part try:

int numberOfInches = (100.0 / 254.0) * 101.0;
0

Why not using float ? try 100.0f/254.0f

Isukthar
  • 185
  • 8