c - 如何在下面的程序中修改程序以将数组范围设置为 0 到 100
问题描述
我需要下面的代码来识别输入的成绩是低于 1 还是大于 100。如果不在参数范围内,我想让用户知道并允许他们输入另一个成绩而不退出程序或失去他们的成绩已经进入。我不希望程序在用户输入 q 之前退出,并且我想确保当时输入的所有有效成绩都打印出来。我尝试了很多方法,但没有得到正确的结果。我想我可能需要其他一些 if 语句,但我一直无法找到合适的工作。您可以分享任何让我走上正轨的信息,我们将不胜感激。
#include <stdio.h>
#include <stdlib.h>
int main()
{
char choice;
int gradeArray[100];
int grades;
int gCount=0,i;
for(gCount=0; gCount<100; gCount++)
{
//for loop to read the grades till array size
printf("******Enter Choice Selection in Parenthesis******\n Add grades(a)\n Quit(q) \n");
scanf("%c",&choice);
if(choice == 'a' || 'A')
{
//if user choice is a, then read the grade
printf( "Enter grade: ");
scanf("%d", &grades);
getchar();
gradeArray[gCount] = grades; //add the grade to array
}
if(choice == 'q') //if the user choice is q, then exit the loop
{
break;
}
}
printf("Grades are:\n");
for(i=0; i<gCount; i++)
{
printf(" %d%%\n", gradeArray[i]); //print grades
}
return 0;
}
解决方案
您可以执行一个 while 循环来验证用户输入。一段时间后,您将能够强制用户输入正确的成绩。
if(choice == 'A' || choice == 'a'){
printf("Enter grade:");
scanf("%d", &grades);
getchar();
while(grade < 1 || grade > 100){
printf("You entered a wrong number\n");
printf("Enter a grade between 1 and 100: ");
scanf("%d", &grades);
getchar();
}
gradeArray[gCount] = grades;
}
推荐阅读
- c# - 调试asp.net mvc框架源码时出现“No symbol has been loaded for this document”
- swift - 在Swift中将String拆分为长度为1的字符串数组
- python - Lief 不会安装 | 无法为信仰造轮子
- javascript - 如何使用javascript和html一键向firebase数据库中的所有子项添加新数据
- proxy - 在 AWS 上使用代理文件构建 Angular-Cli
- c# - AJAX 部分回发面板破坏了我的按钮?
- linux - 如何让openssl验证下载文件的MAC?
- ios - iOS 自定义相机 - 即刻拍照
- c# - 在 C# 应用程序中连接到 Mariadb
- php - PHP 正则表达式转换为数组