【问题标题】:Same code gives different answer in C and Java, can you help me?相同的代码在 C 和 Java 中给出不同的答案,你能帮我吗?
【发布时间】: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=&lt;random_number&gt;+counter
  • @moveaway00 不,编译器不会用任何值填充堆栈。那将浪费cpu周期。堆栈内存将仅包含上次使用时发生的所有内容。
  • @moveaway00 操作系统不是编译器。所以是的,操作系统确实使用初始化(零)数据设置了堆栈。但不是编译器。到 main 运行时,堆栈已经被使用了很多次。 main 之前有代码运行。

标签: java c portability


【解决方案1】:

在你编写的 C 代码中

int sum, counter = 1;

这意味着总和没有用值初始化。
与 Java 不同,C 中 int 的默认值不为零。请查看问题here 了解更多详细信息。

此值可能是垃圾值,您的代码将添加到该值而不是零,从而产生无效结果。

要修复您的代码,只需在声明变量时初始化 sum。

 int sum = 0;
 int counter = 1; 

【讨论】:

    【解决方案2】:

    您的代码中的问题是您没有初始化变量sum

    sum 的值在未初始化时是未定义的。因此 sum 将取当前内存中的值,这会产生这样的不准确性。

    将变量sum初始化为0,你应该得到正确的结果。

    【讨论】:

    • 工作。我以为它会初始化为零。现在,我将确保在初始化变量时牢记这个问题。谢谢。
    • @EzequielBarbosa 很高兴。请记住,初始化变量始终是一种好习惯,即使您必须初始化为 0 或 NULL。
    • 好的,我会记录下来。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    • 2023-03-11
    • 2019-09-19
    • 1970-01-01
    • 2015-04-02
    相关资源
    最近更新 更多