Int64算术错误

时间:2013-04-02 22:07:51

标签: c# largenumber

为什么输出“0和0”?我如何解决它?

 Int64 small=  (long)0.25 * (long)Int64.MaxValue;
 Int64 large = (long)0.75 * (long)Int64.MaxValue;
 System.Console.WriteLine(small + " and " + large);
 System.Console.ReadLine(); 
 //output 
 //0 and 0 

4 个答案:

答案 0 :(得分:3)

语句(long)0.75将返回0(将double转换为long将取最大整数值,即转换为double的较低值)。所以你有0 * 9223372036854775807,希望0。顺便说一句longInt64的别名,这意味着它们是相同的基础类型,因此(long)Int64.MaxValuelong投射到{{ 1}}

要修复它,只需使用long * double乘法

long

不要打扰long small= (long)(0.25 * long.MaxValue); long large = (long)(0.75 * long.MaxValue); Console.WriteLine ("{0:N}", small); //print 2,305,843,009,213,693,952.00 Console.WriteLine ("{0:N}", large); //print 6,917,529,027,641,081,856.00 字面值,它只是一种格式,可以为输出提供一些视觉美感。默认情况下,double以科学计数法打印,这是不可证明的(例如,"{0:N}"用于第一次操作)

答案 1 :(得分:0)

原因在于,在两种情况下,您都要将小于1的值转换为long。这会将值截断为0,因此乘法也会导致0

Console.WriteLine((long)0.25);  // 0
Console.WriteLine((long)0.75);  // 0

答案 2 :(得分:0)

因为0.25和0.75铸造的长度为0。

为了解决这个问题,你需要使用浮动或双打。但是,我并不是100%肯定精确度足以导致确切的结果:

Int64 small=  (Int64)(0.25 * (double)Int64.MaxValue);
Int64 large = (Int64)(0.75 * (double)Int64.MaxValue);

答案 3 :(得分:0)

您希望在乘法之前进行转换。尝试

 Int64 small=  (long) (0.25 * (double) Int64.MaxValue);

在您将.25转换为long 0之前。