在C中结束这个嵌套循环 [英] End this nested loop in C.
问题描述
#include <stdio.h>
#include <limits.h>
int main ()
{
/* variable definition: */
char StudentName[100];
char end;
float ExamValue, Sum, Avg;
int students,exams;
// Loop through Students
for (students=1; students <INT_MAX ; students++)
{
// reset Sum to 0
Sum =0.0;
printf("Enter Student Name \n");
scanf("%s", StudentName);
// Nested Loop for Exams
for (exams=0; exams < 3; exams++)
{
printf ("Enter exam grade: \n");
scanf("%f", &ExamValue);
Sum += ExamValue;
}
Avg = Sum/3.0;
printf( "Average for %s is %f\n",StudentName,Avg);
if (StudentName == 'end')
break;
}
return 0;
}
我的尝试:
我已经尝试了各种版本,但仍然没有。
What I have tried:
I have tried various versions of this and still nothing.
推荐答案
这甚至都不会编译,因为最后的if语句不正确。
That will not even compile because the if statement at the end is incorrect.
if (StudentName == 'end')
break;
您无法以这种方式比较字符串,并且您正在尝试比较字符数组,而不是单个字符。字符串 end 也必须是双引号。替换为以下内容:
You cannot compare strings in this way, and you are trying to compare a character array, not a single character. Also the string end must be in double quotes. Replace it with the following:
if (strcmp(StudentName, "end") == 0)
break;
首先正确地缩进你的代码,所以它看起来不像是一个虚假的大括号:
Start by indenting your code correctly so it doesn't look like it ends with a spurious close curly bracket:
#include <stdio.h>
#include <limits.h>
int main ()
{
/* variable definition: */
char StudentName[100];
char end;
float ExamValue, Sum, Avg;
int students,exams;
// Loop through Students
for (students=1; students <INT_MAX ; students++)
{
// reset Sum to 0
Sum =0.0;
printf("Enter Student Name \n");
scanf("%s", StudentName);
// Nested Loop for Exams
for (exams=0; exams < 3; exams++)
{
printf ("Enter exam grade: \n");
scanf("%f", &ExamValue);
Sum += ExamValue;
}
Avg = Sum/3.0;
printf( "Average for %s is %f\n",StudentName,Avg);
if (StudentName == 'end')
{
break;
}
}
return 0;
}
现在我要看的是将函数中的退出测试提高,这是你做的第一件事:
Now what I would look at is moving the "exit test" higher in the function, so that it's the first thing you do:
#include <stdio.h>
#include <limits.h>
int main ()
{
/* variable definition: */
char StudentName[100];
char end;
float ExamValue, Sum, Avg;
int students,exams;
// Loop through Students
for (students=1; students <INT_MAX ; students++)
{
printf("Enter Student Name \n");
scanf("%s", StudentName);
if (strcmp(StudentName, "end") == 0)
{
break;
}
Sum =0.0;
for (exams=0; exams < 3; exams++)
{
printf ("Enter exam grade: \n");
scanf("%f", &ExamValue);
Sum += ExamValue;
}
Avg = Sum/3.0;
printf( "Average for %s is %f\n",StudentName,Avg);
}
return 0;
}
如果这不能解决您的问题,那么您需要更详细地解释您正在做什么,而不是您没想到的,或者没有这样做。您已经做了些什么来找出原因 - 包括调试器在您的代码运行时向您显示的内容。
If that doesn't fix your problem, then you need to explain in a lot more detail exactly what it is doing that you didn't expect, or not doing that you did. And what you have done to find out why - including what the debugger showed you while your code was running.
这篇关于在C中结束这个嵌套循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!