为什么这些除法方程的结果为零? [英] Why do these division equations result in zero?
问题描述
下面 for 循环中所有除法方程的结果都是 0.我怎样才能让它给我一个小数,例如:
The result of all of the division equations in the below for loop is 0. How can I get it to give me a decimal e.g.:
297 / 315 = 0.30793650793650793650793650793651
代码:
using System;
namespace TestDivide
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i <= 100; i++)
{
decimal result = i / 100;
long result2 = i / 100;
double result3 = i / 100;
float result4 = i / 100;
Console.WriteLine("{0}/{1}={2} ({3},{4},{5}, {6})", i, 100, i / 100, result, result2, result3, result4);
}
Console.ReadLine();
}
}
}
答案:
谢谢 Jon 和大家,这就是我想做的:
Answer:
Thanks Jon and everyone, this is what I wanted to do:
using System;
namespace TestDivide
{
class Program
{
static void Main(string[] args)
{
int maximum = 300;
for (int i = 0; i <= maximum; i++)
{
float percentage = (i / (float)maximum) * 100f;
Console.WriteLine("on #{0}, {1:#}% finished.", i, percentage);
}
Console.ReadLine();
}
}
}
推荐答案
您使用的是 int/int,它可以执行整数算术中的所有操作,即使您要分配给小数/双精度/浮点变量也是如此.
You're using int/int, which does everything in integer arithmetic even if you're assigning to a decimal/double/float variable.
强制操作数之一为您要用于算术的类型.
Force one of the operands to be of the type you want to use for the arithmetic.
for (int i = 0; i <= 100; i++)
{
decimal result = i / 100m;
long result2 = i / 100;
double result3 = i / 100d;
float result4 = i / 100f;
Console.WriteLine("{0}/{1}={2} ({3},{4},{5}, {6})",
i, 100, i / 100d, result, result2, result3, result4);
}
结果:
0/100=0 (0,0,0, 0)
1/100=0.01 (0.01,0,0.01, 0.01)
2/100=0.02 (0.02,0,0.02, 0.02)
3/100=0.03 (0.03,0,0.03, 0.03)
4/100=0.04 (0.04,0,0.04, 0.04)
5/100=0.05 (0.05,0,0.05, 0.05)
(等)
请注意,并没有显示由浮点数或双精度数表示的确切值 - 例如,您不能将 0.01 精确地表示为浮点数或双精度数.字符串格式有效地四舍五入结果.请参阅我的 关于 .NET 浮点二进制点的文章了解更多信息以及一个类将让您看到双精度值的精确值.
Note that that isn't showing the exact value represented by the float or the double - you can't represent 0.01 exactly as a float or double, for example. The string formatting is effectively rounding the result. See my article on .NET floating binary point for more information as well as a class which will let you see the exact value of a double.
我没有为 result2
使用 100L 而烦恼,因为结果总是一样的.
I haven't bothered using 100L for result2
because the result would always be the same.
这篇关于为什么这些除法方程的结果为零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!