简体   繁体   English

为什么我看不到C#中的小数点数字?

[英]why cant i see the decimal point numbers in c#?

int total = 201;

double Average = total / 7;

result should be 28.71428571428571.

I've tried float, decimal and double for Average but the result ends up as 28. 我曾尝试对平均值进行浮点,小数和双精度运算,但结果最终为28。

You are doing integer division! 您正在做整数除法!

201/7 is entirely integral, and so the result doesn't even touch floats, instead you need to cast to a double first: 201/7是完全不可或缺的,因此结果甚至不涉及浮点数,相反,您需要先201/7转换为double:

double Average = (double)total / 7.0;

It's doing integer arithmetic, because total is an int, and 7 is an int. 它正在执行整数算术,因为total是一个int,而7是一个int。 If you change either of them to decimal you'll get the result you're looking for. 如果将它们中的任何一个都更改为十进制,则将得到所需的结果。

eg 例如

int total = 201;

double Average = total / 7.0;

You can use the D suffix to implicitly state the operand is a double, for example: 您可以使用D后缀隐式声明操作数为双精度型,例如:

201 / 7
28

201 / 7D
28.714285714285715

Or: 要么:

double Average = total / 7D;

Because an int divided by an int is always an int. 因为一个整数除以一个整数总是一个整数。

try this: 尝试这个:

double average = total / 7.0;

the total is int and 7 is int. 总数是int,7是int。 The resul of integer division is int. 整数除法的结果为int。 It gets cast AFTER that to double but this does not matter because it is already truncated. 它会在翻倍后强制转换,但这无关紧要,因为它已经被截断了。 Try: 尝试:

double average = total / 7.0;

7.0 is a double literal and the result of int and double division is double. 7.0是双精度字面量,int和double除法的结果是double。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM