我想知道这是否是某种结合性问题,因为当我在纸上做这个问题时,我得到了正确的答案,但是当我运行代码时,我会一遍又一遍地得到4。这是密码。为什么这些不平等?我遗漏了什么?
整个问题(每次迭代返回4):
for (int x = 1; x <= stackCount; x++) {
temp = ((x - 1) / stackCount * uBound) + lBound + 1;
Base[x] = Top[x] = Convert.ToInt32(Math.Floor(temp));
}破碎成碎片(正确运行):
double temp, temp1, temp2, temp3, temp4;
for (int x = 1; x <= stackCount; x++) {
temp1 = (x - 1);
temp2 = temp1 / stackCount;
temp3 = temp2 * uBound;
temp4 = temp3 + lBound + 1;
Base[x] = Top[x] = Convert.ToInt32(Math.Floor(temp4));
}补充说:是的,对不起,我忘记了那份声明:
//the main memory for the application
private string[] Memory;
//arrays to keep track of the bottom and top of stacks
private int[] Base;
private int[] Top;
//keep track of the upper and lower bounds and usable size
private int LowerBound;
private int UpperBound;
private int usableSize;我也觉得我倒过来了。我认为,如果在带整数的除法运算中使用了double,则结果将是double,但情况似乎并非如此。这事儿可以理解!谢谢大家!
发布于 2014-04-02 23:40:58
推测:stackCount、uBound和lBound都是整数或多头。
结果:整个表达式都是计算出来的,就像在做整数运算一样。
解决方案:temp = ((double)(x -1) / stackCount * uBound) + lBound + 1;
发布于 2014-04-03 00:20:47
你还没给我们完整的密码。特别是,stackCount、uBound、lBound和temp的声明都被省略了。您还省略了前3的值。
如果,就像看上去一样,所有与你的表情相关的部分
((x - 1) / stackCount * uBound) + lBound + 1;如果是整数类型,则结果也将是整数除法后的整数类型:
int x = 9 ;
int y = 4 ;
double z = x / y ;产生预期的双精度值2.0。
((5 - 1) / 9 * 11) + 3 + 1表达式解析2的特定整型取决于所涉及的各种类型以及它们是否被签名,以及它们是否都是兼容的。
https://stackoverflow.com/questions/22825141
复制相似问题