What's wrong with this division? [closed]

2020-01-29 18:47发布

问题:

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 7 years ago.

I think there's a lot for me to learn about data types. Why this happens

double result = ((3/8)*100).ToString();

it gives zero .. should be 37,5 ... :(

回答1:

3/8 performs an integer division and the result is 0

double result = ((3.0/8)*100);

should do it.

By the way, if you do ((3.0/8)*100).ToString() you get a String and not a double.



回答2:

double result = ((3.0/8.0)*100);

Should do it. You were performing integer division, not floating point division.



回答3:

You need to convince the compiler to perform floating point division:

double result = (((double)3/8)*100);

Otherwise it performs integer division and 3/8 is zero then.



回答4:

Your expression involves only integers, and 3/8 is 0.

If you want a floating-point expression, at least one element of the expression must be floating point.

The simplest solution is the following:

double result = (100.0 * 3/8)

Note that I put the hundred factor first because it helps having a better precision to do the multiplications before the divisions.

Also, the toString() is strange??



回答5:

The integer division (3/8) yields 0. If you want to work with floating point values, make that clear to your programming language (3.0/8.0 or 3f/8f or 3d/8d or whatever else your language allows)



回答6:

3 & 8 are integers, so the result of 3/8 is also an integer unless you cast it differently.

So, 3/8 = 0.



回答7:

The unicorns took away the 3 and replaced it with a 0.

On the off chance that this is a real question... 3/8 is rounded down to 0. 0* 100 = 0.



回答8:

Because integer math was used, not floating point.

You wrote ((3/8)*100) but none of the constants in that expression have a non-integral type. Therefore the compiler (correctly) interpreted that as integer arithmetic. Since 3/8 is less than 1, the expression evaluates to 0.

A simple fix would be to write ((3./8.)*100.) instead. Actually, making either of the 3 or 8 be a floating point value would be sufficient due to the rules for mixed type expressions.



回答9:

The 3 and the 8 are integers, so 3/8 = 0.

Use:

string result = ((3d/8d)*100d).ToString();


回答10:

3 and 8 in your division are integer literals, so integer division is performed, and 3 / 8 evaluates to zero. If you replace them with 3.0 and 8.0, or use an appropriate data type suffix (you don't say what language you are in) then the calculation will work.



回答11:

3/8 = 0

3.0/8.0 = 0.375