c - 有没有办法制作一个错误计数器,在特定数量的用户输入后终止程序?
问题描述
我是一个编程初学者。我制作了一个将整数输入转换为罗马数字的程序。这是一个非终止程序,只有在用户输入 5 个错误时才会终止。
int main(){
int i;
for(i = 1; i > 0; i++)
{
int num;
printf("\n\nEnter a positive integer: ");
scanf("%d", &num);
while(num == 0 || num < 0 || num > 3999 || i == 5)
{
if(i == 5)
{
int ch;
printf("\n\nYou have reached 5 retries. Do you wish to continue?\n");
printf("Press 1 to continue.\n");
printf("Press 2 to terminate the program.\n");
scanf("%d", &ch);
if(ch == 1)
{
break;
}
else if(ch == 2)
{
return 0;
}
else
{
printf("Invalid input. The program will now terminate.");
return 0;
}
}
else if(num == 0)
{
printf("Error: Zero is Nulla");
break;
}
else if(num < 0)
{
printf("Error: Input cannot be negative");
break;
}
else if(num > 3999)
{
printf("Error: Input cannot be greater than 3999");
break;
}
else
{
printf("Error: Input should be a positive integer");
break;
}
}
while(num > 0 && num <4000)
{
if (num >= 1000) // 1000 - m
{
printf("m");
num -= 1000;
}
else if (num >= 900) // 900 - cm
{
printf("cm");
num -= 900;
}
else if (num >= 500) // 500 - d
{
printf("d");
num -= 500;
}
else if (num >= 400) // 400 - cd
{
printf("cd");
num -= 400;
}
else if (num >= 100) // 100 - c
{
printf("c");
num -= 100;
}
else if (num >= 90) // 90 - xc
{
printf("xc");
num -= 90;
}
else if (num >= 50) // 50 - l
{
printf("l");
num -= 50;
}
else if (num >= 40) // 40 - xl
{
printf("xl");
num -= 40;
}
else if (num >= 10) // 10 - x
{
printf("x");
num -= 10;
}
else if (num >= 9) // 9 - ix
{
printf("ix");
num -= 9;
}
else if (num >= 5) // 5 - v
{
printf("v");
num -= 5;
}
else if (num >= 4) // 4 - iv
{
printf("iv");
num -= 4;
}
else if (num >= 1) // 1 - i
{
printf("i");
num -= 1;
}
}
}
return 0;}
它在 5 次用户输入后停止,但我不希望这样。我希望它在出现 5 个错误后停止。任何帮助,将不胜感激。谢谢
解决方案
i
在循环的每次迭代中递增,这就是它在 5 次迭代(5 个用户输入)后停止的原因。所以:
- 而不是
for
循环,你应该有一个while(1)
循环。 - 而不是,在主循环之前
int i;
做一个。int error_counter = 0;
- 然后代替
if(i == 5)
,你可以写++error_counter; if (error_counter == 5) { ... }
。 - 此外,两个内部“while”循环实际上只是“if”条件。所以代替
while(num == 0 || num < 0 || num > 3999 || i == 5)
andwhile(num > 0 && num <4000)
,你应该只使用if (num <= 0 || num > 3999) {...} else {...}
推荐阅读
- selenium - 编译 selenium webdriver 源 - 降压问题
- android - 如何更改选项卡布局中选择的选项卡的颜色
- javascript - tinymce - 无法从编辑器中删除细黑色轮廓
- tensorflow - 展平张量流数据集中的图像元组
- r - 如何设置文本以在工具提示上显示货币(使用 plot_ly 而不是 ggplotly)?
- c# - 在 C# 中使用 If else 升序排列 5 个数字
- android - Expo Eject 后,run-android 错误:spawnSync gradlew.bat Enoent
- python - python代码中的问题[configparser.InterpolationSyntaxError:'%'必须后跟'%'或'(',找到:'%']使用带有appium的python 3.7.3
- r - 如何创建与列交叉的指标向量?
- python - 将 .xlsx 文件导入模型,收到 DateField 的 Integer out of range 错误:行号:1 - integer out of range