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

C语言用结构体写距离求和程序时跳过第二个距离米数输入问题

代码问题分析

你遇到的输入跳过问题由以下错误导致:

  • scanf 不支持 .2 这类精度限定写法,你代码中两处读取厘米值的语句 scanf("%.2f",&l1.centimeter);、scanf("%.2f",&l2.centimeter); 均为无效写法。精度限定仅可用于 printf 控制输出效果,scanf 读取float类型变量时仅需使用 %f 作为格式符即可。
    该错误会导致第一处厘米值输入解析失败,输入缓冲区残留的未处理内容会被后续读取第二个米数的scanf("%d",&l2.meter)尝试读取,类型匹配失败后就会直接跳过输入环节,符合你遇到的现象。
  • 可选优化:可以在所有scanf的格式符前加空格,主动吸收输入缓冲区残留的换行、空格等空白字符,进一步避免意外的输入跳过问题。
修正后可正常运行的代码
#include<stdio.h>

struct distance{
    int meter;
    float centimeter;
}l1,l2,sum;

int main()
{
    printf("Distance 1 : \n");
    printf("Enter the meter value :");
    scanf(" %d",&l1.meter);
    printf("Enter the centimeter value :");
    scanf(" %f",&l1.centimeter);

    printf("Distance 2 : \n");
    printf("Enter the meter value : \n");
    scanf(" %d",&l2.meter);
    printf("Enter the centimeter value :");
    scanf(" %f",&l2.centimeter);


    sum.meter = l1.meter + l2.meter;
    sum.centimeter = l1.centimeter + l2.centimeter;

    while(sum.centimeter >= 100)
    {
        ++sum.meter;
        sum.centimeter-=100;
    }

    printf("The sum of the distances you have entered is %d m and %.2f cm.",sum.meter,sum.centimeter);
    return 0;
}

内容的提问来源于stack exchange,提问作者I am me

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 06:24:06