gpt4 book ai didi

c - 如何强制用户输入一定范围内的正整数起始值

转载 作者:行者123 更新时间:2023-11-30 16:33:30 24 4
gpt4 key购买 nike

如何修复我的代码,以便如果起始值作为负整数输入,它将要求另一个起始值。另外,每次输入起始值和结束值时计算差异的最佳方法是什么?

void inputs(int* starting_value, int* ending_value)
{
int temp; // switch for while loop

temp = 0; // enter while loop

while(temp == 0)
{

printf("Enter starting value of range -> ");
scanf("%d", starting_value);

do
{
printf("Error! Starting value must be non-negative!!\n");
printf("\nEnter starting value of range -> ");
scanf("%d", starting_value);
} while(starting_value < 0); // if input is negative

printf("Enter ending value of range -> ");
scanf("%d", ending_value);

temp = 1; // leave while loop

if (ending_value - starting_value > 5000000) // if the total difference is less than 5000000
{
temp = 0; // restart while loop
printf("\n\nError! The maximum difference between start and end is 5000000\n\n");
}

}
}

最佳答案

将 do-while 更改为检查输入时的 while,如果用户第一次输入 1,他仍然会执行重试逻辑。

最好的方法可能是同时获取两个输入,然后将它们相减。

printf("Enter start and end variables\n");
scanf("%d %d", &start, &end);

while((start < 0) || (end < 0)){ //You can also throw a max range check here too
printf("Enter start and end variables\n");
printf("Make SURE neither value is negative\n");
scanf("%d %d", &start, &end);
}

//subtract or do whatever else after both inputs are non negative

关于c - 如何强制用户输入一定范围内的正整数起始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49741570/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com