由于某种原因,我在运行该程序时总是收到奇怪的运行时错误。它可以很好地编译,并且大多数程序都可以运行。
代码:
#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);
}
}
问题似乎出teams[3]
在最后一个for循环中。无论我做什么,它在打印后崩溃printf("Team Name | Games Played | Games Won | Percentage");
库GetInteger()
和GetLine()
是我用来从simpio.h库获取输入的两个函数。任何帮助,将不胜感激。
编辑:如果数组索引从0开始,那么team [3]不应该有四个元素吗?(0,1,2,3)
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开始,那么team [3]不应该有for元素吗?(0,1,2,3)
答:不可以。该数组的大小为3,因此可以容纳3个元素,第一个位于第0个单元格中,第二个位于第一个单元格中,第三个位于第二个单元格中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句