C中奇怪的运行时错误?

雅典

由于某种原因,我在运行该程序时总是收到奇怪的运行时错误。它可以很好地编译,并且大多数程序都可以运行。

代码:

#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] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

C中的运行时错误(CodeChef)

来自分类Dev

C ++中运行时的分段错误

来自分类Dev

C ++中的运行时错误

来自分类Dev

C ++代码中的运行时错误

来自分类Dev

代码C ++中的运行时错误

来自分类Dev

奇怪的错误Django运行时

来自分类Dev

运行for循环时出现奇怪的运行时错误'424'

来自分类Dev

分析时间时C ++中的运行时错误

来自分类Dev

循环和运行时错误中的C ++变量声明

来自分类Dev

C ++中动态内存分配的运行时错误

来自分类Dev

C ++中的指针和运行时错误

来自分类Dev

使用C在Spoj中运行时NZEC错误

来自分类Dev

为什么 bfs c ++ 中的运行时错误

来自分类Dev

C++ 工厂模式中的运行时错误

来自分类Dev

在Django模板中循环DefaultDict时出现奇怪的运行时错误

来自分类Dev

在Django模板中循环DefaultDict时出现奇怪的运行时错误

来自分类Dev

FF Addon SDK 1.17运行时出现奇怪错误

来自分类Dev

奇怪的运行时错误声明类Java的实例

来自分类Dev

奇怪的运行时错误,fprintf写的超出要求

来自分类Dev

Perl中的运行时错误

来自分类Dev

seekbar Android中的运行时错误

来自分类Dev

customAdapter中的运行时错误

来自分类Dev

pymel中的运行时错误

来自分类Dev

Perl中的运行时错误

来自分类Dev

Java中的NZEC运行时错误

来自分类Dev

UVa 594中的运行时错误

来自分类Dev

在线判断中的运行时错误

来自分类Dev

应用中的Android运行时错误

来自分类Dev

customAdapter中的运行时错误