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

C语言输入的height与length值不保存,打印始终为0问题求助

问题根因

  • scanf格式符和变量类型不匹配:你定义的变量为float类型,但scanf中使用的%lf是double类型对应的输入格式符,float对应的正确输入格式符为%f,类型不匹配导致输入值没有被正确写入变量,因此后续计算结果始终为0。
  • scanf不支持精度限定:你写的%.2lf属于错误用法,只有printf输出时可以指定保留小数位数,scanf输入时不能加.2这类精度修饰符,会直接导致输入解析失败。
  • fflush(stdin)属于未定义行为:C标准明确规定fflush仅对输出流生效,对输入流stdin调用fflush的行为没有标准约束,部分编译器可能支持但不具备通用性,也可能引发输入流处理异常。

修正后代码

#include <stdio.h>
#include <stdlib.h>

int main()
{
    float xHeight,yHeight,xLength,yLength, height = 0.0, length = 0.0;

    printf("Tell me the x and y: \n");
    scanf("%f", &xHeight);
    // 清理输入缓冲区残留换行符,替代fflush(stdin)
    while(getchar() != '\n');
    scanf("%f",&yHeight);
    while(getchar() != '\n');

    height = xHeight - yHeight;
    printf("\n%.2f",height);

    printf("Now tell me another x and y: \n");
    scanf("%f", &xLength);
    while(getchar() != '\n');
    scanf("%f",&yLength);
    while(getchar() != '\n');

    length = xLength - yLength;
    printf("\n%.2f", length);

    printf("\n==========================================\n");

    printf("The perimeter of this rectangle is %.2f", 2*(length+height));

    return 0;
}

改动说明

  • 所有scanf的格式符替换为%f匹配float类型,保留两位小数的需求仅在printf中通过.2f指定即可。
  • 用while(getchar() != '\n')替代fflush(stdin),安全清理输入缓冲区的残留换行符,避免后续scanf读取到无效空值。
  • 删除了height赋值行多余的重复分号。

内容的提问来源于stack exchange,提问作者Boropap

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 09:54:05