C#:将一个整数除以100 [英] C#: divide an int by 100

查看:740
本文介绍了C#:将一个整数除以100的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 int 除以100?

例如:

int x = 32894;
int y = 32894 / 100;

为什么会导致 y 328 而不是 328.94

Why does this result in y being 328 and not 328.94?

推荐答案

当一个整数除以另一个时,该算术被执行为 整数算术。

When one integer is divided by another, the arithmetic is performed as integer arithmetic.

如果要执行作为浮点,双精度或十进制算术,您需要适当地转换其中一个值。例如:

If you want it to be performed as float, double or decimal arithmetic, you need to cast one of the values appropriately. For example:

decimal y = ((decimal) x) / 100;

请注意,我更改了 y -执行十进制算术没有意义,而是将结果存储在 int 中。 int 不可能存储328.94。

Note that I've changed the type of y as well - it doesn't make sense to perform decimal arithmetic but then store the result in an int. The int can't possibly store 328.94.

您只需要强制一个值类型正确,然后另一个将被提升为相同类型-例如,没有定义用于将小数除以整数的运算符。如果要使用多个值进行算术运算,可能只是为了清楚起见就将所有全部强制为所需的类型-不幸的是,一个操作要使用整数算术执行,而另一个操作要使用整数算术执行

You only need to force one of the values to the right type, as then the other will be promoted to the same type - there's no operator defined for dividing a decimal by an integer, for example. If you're performing arithmetic using several values, you might want to force all of them to the desired type just for clarity - it would be unfortunate for one operation to be performed using integer arithmetic, and another using double arithmetic, when you'd expected both to be in double.

如果您使用文字,则可以使用后缀来指示类型:

If you're using literals, you can just use a suffix to indicate the type instead:

decimal a = x / 100m; // Use decimal arithmetic due to the "m"
double b = x / 100.0; // Use double arithmetic due to the ".0"
double c = x / 100d; // Use double arithmetic due to the "d"
double d = x / 100f; // Use float arithmetic due to the "f"

使用浮点运算,至于是否应使用十进制 double float ,这取决于您所尝试的操作去做。阅读十进制浮点二进制浮点。如果您要处理自然数量(例如身高和体重),其中任何值实际上是近似值,通常 double 是合适的; 十进制适用于诸如金钱之类的人工数量,通常以精确地表示为十进制值

As for whether you should be using decimal, double or float, that depends on what you're trying to do. Read my articles on decimal floating point and binary floating point. Usually double is appropriate if you're dealing with "natural" quantities such as height and weight, where any value will really be an approximation; decimal is appropriate with artificial quantities such as money, which are typically represented exactly as decimal values to start with.

这篇关于C#:将一个整数除以100的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆