对于我的硬件分配,我必须创建一个程序,根据用户输入输出基于星号的三角形。我已经让我的程序正常工作,只要用户输入一个整数,就会输出正确的三角形,但我的问题是,当输入无效值时,如何使用户必须重新尝试提交值?我查看了论坛,但没有找到类似的问题。
#include <stdio.h>
int main() {
int lines, a, b;
//prompt user to input integer
printf("Input a value from 1 to 15: ");
scanf("%d", &lines);
//Check if inputed value is valid
if(lines >= 1 && lines <= 15) {
/*create triangle based on inputed value */
for(a = 1; a <= lines; a++) {
for(b=1; b<= a; b++) {
printf("*");
}
printf("\n");
}
}
else {
printf("not valid");/* repeat code in this else statement, maybe */
}
system("pause");
}
#include <stdio.h>
int main() {
int lines, a, b;
//prompt user to input integer
do{
printf("Input a value from 1 to 15: ");
scanf("%d", &lines);
//Check if inputed value is valid
if(lines < 1 || lines > 15) {
printf("Error: Please Enter a Valid number!!!\n");
continue;
}
/*create triangle based on inputed value */
for(a = 1; a <= lines; a++) {
for(b=1; b<= a; b++) {
printf("*");
}
printf("\n");
}
}while(1);
system("pause");
}
如果您想在用户输入有效值(我的意思是 1-15)时停止程序,则将这些 for 循环放入 else 块中并添加 break 语句。
do{
printf("Input a value from 1 to 15: ");
scanf("%d", &lines);
//Check if inputed value is valid
if(lines < 1 || lines > 15) {
printf("Error: Please Enter a Valid number!!!\n");
continue;
}
else{
/*create triangle based on inputed value */
for(a = 1; a <= lines; a++) {
for(b=1; b<= a; b++) {
printf("*");
}
printf("\n");
}
break;
}
}while(1);
system("pause");
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)