我正在使用 DEV c++。 刚刚面临一个非常奇怪的问题。
首先,我复制运行良好的程序的代码。
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<time.h>
#define f(x) 0.2027*sqrt(1-x*x)
int main()
{
int k=0; //<----the change is here
float x,y,c,z;
c=0.6366198;
do {
x=2*(rand()/(float)RAND_MAX)-1;
z=rand()/(float)RAND_MAX;
y=y*2*c;
if (y<=f(x)) {
printf("%f\t",x);
k=k+1;
}
} while(k<=100); // <--the change is here
getchar();
}
如果我稍微改变 while 条件以使程序更通用一点,那么在 DEVc++ 中什么也不会发生。我只看到一个“空白页”;
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<time.h>
#define f(x) 0.2027*sqrt(1-x*x)
int main()
{
int k=0,t=100; //<----the change is here
float x,y,c,z;
c=0.6366198;
do {
x=2*(rand()/(float)RAND_MAX)-1;
z=rand()/(float)RAND_MAX;
y=y*2*c;
if (y<=f(x)) {
printf("%f\t",x);
k=k+1;
}
} while(k<=t); // <--the change is here
getchar();
}
在turboc++中也发生了同样的事情。它不是像 Devc++ 那样显示空白页,而是显示浮点溢出。为什么?
最佳答案
正如我所见,在你的代码中
y=y*2*c;
y
在未初始化的情况下使用。作为自动局部变量,初始值是不确定的。因此,您的两个代码都会调用 undefined behavior .
引用标准,第 §6.7.9 章,初始化
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. [...]
对于未定义的行为,请参见附件§J.2
The value of an object with automatic storage duration is used while it is indeterminate
您需要初始化自动局部变量,例如
float x = 1, y = 2, c = 3, z = 4; //values are for example purpose
等等。
这个故事的寓意:请打开编译器警告并注意它们。
关于c++ - 两个程序具有相同的代码: floating point overflow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34856298/