为什么声明一个clock_t类型的整数会改变我的C程序?

时间:2015-03-03 22:45:02

标签: c

我实际上能够找出我的程序有什么问题。

我可以通过添加如下行来打破程序:

clock_t a_clock;

我命名这个变量并不重要,只是它是类型clock_t,我声明它。

我不一定要为它分配任何东西,或者甚至尝试计算我的程序。

这是整个程序的pastebin。 您可以尝试自己编译和运行程序。 如果你拿出" clock_t a_clock"它会计算PI到一定程度的准确度。行:

http://pastebin.com/1jdyiKnR

以下是PI的错误计算,我的程序输出:

Here is my_init 3533980296
Skipped first 100 results
Calculating PI from random numbers
total_count 1610725872 c_count 78541369
x 0.071707 y -0.055589
Guess for PI = 0.195046 with 100000000 iterations

1 个答案:

答案 0 :(得分:6)

编译:

$ gcc -O3 -std=c99 -Wall -lm test.c

test.c:59:9: warning: ‘total_count’ is used uninitialized in this function [-Wuninitialized]
     int total_count, c_count = 0;

(还有一些关于未使用代码的无害警告)

也就是说,您total_count未初始化,只需将其设置为0即可按预期工作:

 int total_count = 0, c_count = 0;

请记住,使用uninitizalied变量是未定义的行为。通过声明一个额外变量来改变结果的事实只是偶然的。