【发布时间】:2015-06-25 20:38:38
【问题描述】:
这些分别用 C 和 Java 编写的 sn-ps 应该输出相同的结果,但它们没有,而且我无法确定错误在哪里。
用 C 语言编写
#include <stdio.h>
/* discover and print all the multiples of 3 or 5
below 1000 */
int main() {
int sum, counter = 1;
while (counter < 1000) {
printf("Calculating...\n");
printf("%d numbers already verified.\n", counter);
if ( counter % 3 == 0 || counter % 5 == 0 ) {
sum += counter;
}
++counter;
}
printf("The sum of all multiples is: %d", sum);
return 0;
}
Java:
package problems;
//Prints the sum of all the multiples of 3 or five below 1000
public class Problem1 {
public static void main(String[] args) {
int sum = 0, counter = 1;
while (counter < 1000) {
System.out.format("Calculating...%n");
System.out.format("%d numbers already verified.%n",counter);
if( (counter % 3 == 0) || (counter % 5 == 0) ) {
sum += counter;
}
++counter;
}
System.out.format("The sum of all multiples is: %d", sum);
}
}
C 输出 2919928 作为总和,而 Java 输出 233168。
【问题讨论】:
-
您从未在 C 代码中初始化 sum 的值。你应该总是用
-Wall编译C。正确的总和确实是 233168。 -
@jwilner 我的猜测是 sum 的值在未初始化时是未定义的。因此 sum 将取当前内存中的值,这会产生这样的不准确性。
-
因为在 C 中未初始化的本地(堆栈)变量可以具有任何随机值。因此,当您执行
sum+=counter时,您实际上是在执行sum=<random_number>+counter。 -
@moveaway00 不,编译器不会用任何值填充堆栈。那将浪费cpu周期。堆栈内存将仅包含上次使用时发生的所有内容。
-
@moveaway00 操作系统不是编译器。所以是的,操作系统确实使用初始化(零)数据设置了堆栈。但不是编译器。到 main 运行时,堆栈已经被使用了很多次。 main 之前有代码运行。
标签: java c portability