What's wrong with this division? [closed]

2020-01-29 19:10发布

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 ... :(

11条回答
The star\"
2楼-- · 2020-01-29 19:27

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

Use:

string result = ((3d/8d)*100d).ToString();
查看更多
【Aperson】
3楼-- · 2020-01-29 19:31

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楼-- · 2020-01-29 19:37
double result = ((3.0/8.0)*100);

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

查看更多
Animai°情兽
5楼-- · 2020-01-29 19:39

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.

查看更多
仙女界的扛把子
6楼-- · 2020-01-29 19:41

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

So, 3/8 = 0.

查看更多
倾城 Initia
7楼-- · 2020-01-29 19:44

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)

查看更多
登录 后发表回答