简体   繁体   English

C#中的分工问题

[英]Problems with division in C#

How can I check if 204 / 5 is greater than 200 / 5? 如何检查204/5是否大于200/5? I experienced difficulty when I attempted this, using both floating-point and decimal math. 我尝试使用浮点和十进制数学时遇到了困难。

Using float or decimal will work... but you need to perform the arithmetic in floating point by making at least one of the operands decimal/float/double: 使用float或decimal 起作用......但是你需要通过至少生成一个十进制/ float / double操作数来执行浮点运算

decimal x = ((decimal) 204) / 5;
decimal y = ((decimal) 200) / 5;

if (x > y) // Yes!

Or use floating point literals: 或者使用浮点文字:

decimal x = 204m / 5;
decimal y = 200m / 5;

It doesn't matter which operand is floating point: 哪个操作数是浮点并不重要:

decimal x = 204 / 5m;
decimal y = 200 / 5m;

float/double work just as well: 漂浮/双重工作:

double x = 204d / 5;
double y = 200d / 5;

So, what's going on if you just use 204 / 5? 那么,如果你只使用204/5会发生什么? Well, consider this statement: 好吧,请考虑以下声明:

double x = 204 / 5;

The compiler doesn't use the type of the variable to work out the type of the right hand side. 编译器不使用变量的类型来计算右侧的类型。 It works out that the right hand side is just an integer, obtained by dividing two integers. 可以看出,右手边只是一个整数,通过划分两个整数得到。 The result is then converted into a double and assigned to x . 然后将结果转换为double并分配给x The problem is that the arithmetic is done purely with integers whereas you want the conversion to floating point to be performed earlier, so that you can get a floating point result. 问题是算术完全是用整数完成的而你希望先前执行转换到浮点,这样你就可以获得浮点结果。

Appending a .0 or an f to any number forces the language to interpret that number as a floating-point decimal: .0f附加到任何数字会强制语言将该数字解释为浮点小数:

  • 204 is an integer, 204是整数,

  • 204f is a single-precision floating-point decimal and 204f是单精度浮点小数和

  • 204.0 is a double-precision floating-point decimal. 204.0是双精度浮点小数。

Therefore, 204/5 returns an integer 40 and 204.0/5 returns a double-precision float 40.8 . 因此, 204/5返回一个整数40204.0/5返回一个双精度浮点40.8

if (204.0/5 > 200.0/5) {
    // stuff
}

Or, you could take the mathematically-simpler route: 或者,您可以采用数学上更简单的路线:

if (204 > 200) {
    // because you're dividing both of them by 5
}
if ((204.0 / 5.0) > (200.0 / 5.0)) {
    //do stuff!
}

The reason is, when you try to calculate 204/5 , it is exactly calculating int 204 divides int 5 , the result is also an int in C#. 原因是,当你尝试计算204/5 ,它正好计算int 204 divides int 5 ,结果也是C#中的int You can try 204m/5 , you will get the correct answer. 你可以尝试204m/5 ,你会得到正确的答案。

if (((float)(204) / 5) > ((float)(200) / 5))
{
//Enter code here
}
else
{
//Enter code here
}

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

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