gpt4 book ai didi

c# - C# 中的乘法错误

转载 作者:太空狗 更新时间:2023-10-29 22:06:32 25 4
gpt4 key购买 nike

当乘以一组 int 并将结果转换为 long 时,我得到的答案与我乘以一组 double 并将结果转换为 long 时不同。例如:

int a = 5;
int b = 5;
int c = 7;
int d = 6;
int ee = 6;
int f = 8;
int g = 9;
int h = 6;
int i = 6;
int j = 4;
int k = 8;
int l = 9;
int m = 5;
long x = a * b * c * d * ee * f * g * h * i * j * k * l * m;

double aa = 5;
double ab = 5;
double ac = 7;
double ad = 6;
double aee = 6;
double af = 8;
double ag = 9;
double ah = 6;
double ai = 6;
double aj = 4;
double ak = 8;
double al = 9;
double am = 5;
long y = (long)(aa * ab * ac * ad * aee * af * ag * ah * ai * aj * ak * al * am);

谁能告诉我为什么会这样?谢谢

最佳答案

你遇到了一个整数溢出,因为每当你将两个 int 相乘时你就会得到 int:到目前为止,这被解释为 Int32

 a * b * c * d * ee * f * g * h * i * j * k * l * m

并且只转换为Int64 (long)。要更正实现,请声明所有变量最初都是 long 例如

  long a = 5;
long b = 5; // actually, not necessary, since a * b will be long, but safer
long c = 7;
...
long m = 5;

long x = a * b * c * d * ee * f * g * h * i * j * k * l * m;

关于c# - C# 中的乘法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27901777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com