简体   繁体   English

与C中的sqrt()函数混淆

[英]Confused with sqrt() function in C

When i do like this, it works well in my code... 当我这样做时,它在我的代码中运行良好...

...

for (i = 2; i <= sqrt(500000); i++)

...

But do like 但是喜欢

for (i = 2; i < sqrt(500000) + 1; i++)

executes after compile, error occurs saying Segmentation fault (core dumped) . 编译后执行,发生错误,说Segmentation fault (core dumped)

for loop body is: for loop body是:

for (i = 2; i <= sqrt(500000); i++) {
        summation[i * i] += i;
        for (j = i + 1; j <= 500000 / i; j++) {
            summation[i * j] += (i + j);
        }
    }

Is there any difference between the two for loops? 这两个for循环之间有什么区别吗? Thanks 谢谢

你的第二个循环再次运行:500000不是一个完美的正方形,所以i < sqrt(500000)i <= sqrt(500000)总是相等,+1确保另一次迭代。

sqrt()将返回一个浮点数,因此所有比较都是针对浮点数进行的,并且它们在设计上是不精确的,因此上面的这两个比较可以产生不同的结果 ,因此在一个案例中你将得到一个 -一个和未定义的行为。

I've tried your code with gcc 4.3.4 under cygwin. 我已经在cygwin下用gcc 4.3.4尝试了你的代码。

  • In the first case, i loops up to 707. 在第一种情况下,我循环到707。
  • In the second case, i loops up to 708. 在第二种情况下,i循环到708。

I bet that this last value triggers a buffer overflow somewhere in the body of the loop. 我敢打赌,这最后一个值会在循环体中的某处触发缓冲区溢出。

As others have already explained, the + 1 causes the loop to iterate once too often. 正如其他人已经解释的那样, + 1导致循环过于频繁地迭代。 Then summation[i * i] or summation[i * j] accesses beyond the allocated size of summation . 然后summation[i * i]summation[i * j]访问超出分配的summation大小。 The solution is to either increase the allocated size accordingly or make sure that the condition is correct (not doing + 1 ) and you thus do not run over the end of the array. 解决方案是相应地增加分配的大小或确保条件正确(不做+ 1 ),因此不会在数组的末尾运行。

But also, like others already said, you should not use a floating point value (result of sqrt ) with an integer comparison as floating point values are... tricky. 但是,就像其他人已经说过的那样,你不应该使用浮点值( sqrt结果)和整数比较,因为浮点值是......棘手的。 I'm not sure whether in this case the int gets casted to float or vice versa, but whichever way it's not the right thing to do. 我不确定在这种情况下int是否会被转换为float,反之亦然,但无论哪种方式都不正确。

did you try this? 你试过这个吗?

for (i = 2; i < (sqrt(500000) + 1); i++)

Is your ia floating pont variable? 你的ia浮动pont变量吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM