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
相关产品推荐
相关产品推荐

