繁体   English   中英

C程序代码辅助

[英]C program code aid

谁能帮助我,并告诉我为什么我的程序不断告诉我值不正确? 我的代码运行并且没有错误。 但是,如果我输入20的高温和10的低温,则printf语句不断出现,表明该值不正确。 但这不是因为我说过,如果高大于40或低小于-40或高大于低! 谁能帮我? 谢谢。

#define NUMS3 
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int high, low;

int main(void)
{ 
    printf("---=== IPC Temperature Analyzer ===--- \n");
    for (int i = 1; i < 4; i++) 
    {
        printf("Enter the high value for day %d:", i);
        scanf("%d", &high);

        printf("Enter the low value for day %d:", i);
        scanf("%d", &low);      
        while (high > 40 || low < -40 || high < low); 
        {
            printf("Incorrect values, temperatures must be in the range "
                   "-40 to 40, high must be greater than low.\n");
        }
    }
    return 0;
}

正如评论中指出的那样,由于使用了立即分号,因此while循环没有主体。

将检查条件,并且while将立即执行printf() 因此,到目前为止, while循环对于highlow值无效。 但是如果循环的条件为真,那将是一个无限循环。

while那里似乎不合适。 您还需要提示用户重新输入正确的值,以防输入无效的值。\\

你可以做类似的事情

if (high > 40 || low < -40 || high < low) 
{
    printf("Incorrect values, temperatures must be in the range - 40 to 40, high must be greater than low.\n");
    i--;
}

代替循环和那个printf()

如果发现无效输入,则会使i减小,以便在i++完成后的循环结束时,变量值保持不变。

编辑:

当您希望输入数字时,用户可能会输入无效的输入(例如字符)。 在这种情况下, scanf()将使输入缓冲区中的输入保持未消耗状态,并且如果在下一次迭代中在scanf()之前没有消耗无效数据,则会出现无限循环。

scanf()返回成功分配的数量。

if( scanf("%d", &high)!=1 )
{
    printf("\nInvalid input.");
    i--;
    consumeBufferData(); //see the link
    continue;
}
if( scanf("%d", &low)!=1 )
{
    printf("\nInvalid input.");
    i--;
    consumeBufferData(); //see the link
    continue;
}

如果发现无效输入,则应使用无效数据。 请参阅这篇文章,以了解有关如何执行此操作的讨论。

就像是

void consumeBufferData()
{
    int c;
    while( (c=getchar())!='\n' && c!=EOF );
}

可能就足够了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM