由于某些原因,当我运行此程序时,我不断收到奇怪的运行时错误。编译很好,大部分程序都可以工作。
代码:
#include <stdio.h>
#include "genlib.h"
#include "simpio.h"
#include <string.h>
main()
{
printf("This program will show you the scores of the basketball games for 1 season.\n");
printf("What is the name of the basketball league? ");
string league = GetLine();
printf("How may games were played by the group? ");
int gamesplayed = GetInteger();
string teams[3];
int wonGames[3];
int a, b, c;
for (a = 0; a < 4; a++)
{
printf("What is team %d's name? ", a+1);
teams[a] = GetLine();
}
for (b = 0; b < 4; b++)
{
printf("How many times did team %s win? ", teams[b]);
wonGames[b] = GetInteger();
}
printf("\n\n ----===[%s]===----\n", league);
printf("Team Name | Games Played | Games Won | Percentage");
for(c = 0; c < 4; c++)
{
double percent = 100 * (wonGames[c]/gamesplayed);
printf("| %s | %d | %d | %lf |", teams[c], gamesplayed, wonGames[c], percent);
}
}
问题似乎是在最后一个for循环中打印teams[3]
。无论我做什么,它在打印printf("Team Name | Games Played | Games Won | Percentage");
库GetInteger()
和GetLine()
是我用来获取输入的两个函数,它来自simpio.h库。任何帮助将不胜感激。
编辑:如果数组索引从0开始,那么团队[3]不应该有四个元素吗? (0,1,2,3)
答案 0 :(得分:6)
string teams[3];
for (a = 0; a < 4; a++)
{
printf("What is team %d's name? ", a+1);
teams[a] = GetLine();
}
您将超出界限,因为teams
的大小为3,而a
最终会获得值3.
索引从0开始到数组大小 - 1.因此将4更改为3,或将大小增加1。
对wonGames
执行相同操作。
同样,应该修改带有计数器c
的循环(如果不增加数组的大小)。
回答编辑。
问:如果数组索引从0开始,那么团队[3]不应该使用元素吗? (0,1,2,3)
答:否。该数组的大小为3,因此它可以容纳3个元素,第一个在第0个单元格中,第二个在第一个单元格中,第三个在第二个单元格中。
答案 1 :(得分:2)
你的阵列&#34;团队&#34;有三个要素。您的打印循环访问四个元素。