m0_57616435 2021-11-17 17:14 采纳率: 66.7%
浏览 37
已结题

C语言,代码中的一段导致无限循环

写题时,代码中的一个 while 语句里出现了无限循环
当输入一个非数字如“fifty”时,while 中的 scanf 还没有输入,就一直出现“The Target weight: Error!”
应该是哪里出错了呢


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

int main()
{
    double w;          // input the target weight
    int check;         // check the return value of scanf
    char c;
    printf("Enter the Target Weight in lbs: ");
    check = scanf("%lf%c", &w, &c);


    // represent weight by available disks -- handle incorrect input
    double dec;                   // dec is the decimals part of w
    int check1, mark=0;           // check1 is a mark used to check if w is a pure number

    while (1)
    {
        if (check == 0 || !isspace(c)){         // Incorret: input is not a pure number
            check1 = 0;
        }
        else {                    // Incorrect: input can't be represented by available disks
            check1 = 1;
            dec = w-(int)w;
            if (dec==0.25 || dec==0.5 || dec==0.75 || dec==0){  
                mark=1;
            }
            else{
                mark=0;
            }
        }
        
        if (check1==0 || w<=0 || w>10000 || mark==0){
            printf("Error!\n");
            printf("The Target Weight: ");
            check = scanf("%lf%c", &w, &c);
        }
        else {
        ;
        }
    }
    return 0;
}

  • 写回答

1条回答 默认 最新

  • CSDN专家-风起峰落 2021-11-17 17:22
    关注

    37行前面增加
    getchar();

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 11月26日
  • 已采纳回答 11月18日
  • 创建了问题 11月17日

悬赏问题

  • ¥15 Matlab在app上输入带有矩阵形式的初始条件发生错误
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 用ADS设计一款的射频功率放大器