gpt4 book ai didi

c - 这样当输入无效值时,用户必须在 C 中重试新值

转载 作者:太空宇宙 更新时间:2023-11-04 04:45:27 25 4
gpt4 key购买 nike

对于我的 HW 作业,我必须创建一个程序来输出一个基于星号的三角形,该三角形取决于用户输入。我已经让我的程序在用户输入整数时输出正确的三角形,但我的问题是当输入无效值时如何使用户必须重新尝试提交值?我查看了论坛,但找不到类似的问题。

#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 block 中并添加 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");
}

关于c - 这样当输入无效值时,用户必须在 C 中重试新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21500789/

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