You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何我的C语言代码在用户输入前就显示变量为0.0000000?

问题原因及修复方案

核心问题

你看到的0.000000是因为在用户输入前就输出了未初始化的变量:

  • 代码里的printf("Input the first number: %f", x);和printf("Input the second number: %f", y);错误地在scanf之前就用%f输出了x和y,但这两个变量刚声明还没被赋值,属于未定义行为(在你的环境里碰巧显示为0,换其他环境可能是随机垃圾值)。
  • 另外,main函数的返回类型不符合C标准,标准要求main返回int而非float,返回值应该是整数0而不是浮点数0.0。

修正后的代码

#include <stdio.h>

/*
Write a C program that accepts two integers from the user then outputs the sum, difference, product, and division of the two integers.
*/

int main()
{
    float x, y; 

    // 只输出提示文字,不要提前打印未初始化的变量
    printf("Input the first number: ");
    scanf("%f", &x);

    printf("Input the second number: ");
    scanf("%f", &y);
    printf("\n");

    // 计算部分保留float类型,保证除法精度
    float sum = x + y;
    float diff = x - y;
    float product = x * y;
    float div = x / y;

    // 输出计算结果
    printf("The sum is: %.2f\n", sum);
    printf("The difference is: %.2f\n", diff);
    printf("The product is: %.2f\n", product);
    printf("The division is: %.2f\n", div);

    return 0;
}

关键说明

  • 保留float类型是正确的,这样像2/3这类计算会得到0.67(而非整数除法的0),满足你要的精度需求。
  • 输入提示只保留文字,去掉多余的%f和变量,这样就不会在输入前输出未初始化的值了。
  • 修正main的返回类型为int,返回整数0符合C语言标准。

内容的提问来源于stack exchange,提问作者Joao Pedro Ferreira

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 12:12:40