为什么我的程序运行正常但有时会输出错误?

时间:2017-07-12 23:58:42

标签: c++ runtime-error

#include "stdafx.h"
#include <iostream>
#include <string>


using namespace std;

int main()
{
    int teams[26];
//Adds A-Z      
    for (int i = 0; i < 26; i++) {
    teams[i] = 65 + i;
    }
    string race;
    cout << "Input uppercase letters indicating the outcome of a race: ";
    cin >> race;
    while (race != "done") {
        int runners[26] = { 0 };
        double scores[26] = { 0 };
    //Checks runners from teams A-Z + add scores up + checks if input is 
    valid
        for (int i = 0; i < 26; i++) {
            for (unsigned int c = 0; c < race.length(); c++) {
                if (race.at(c) == (char)teams[i]) {
                    runners[i] += 1;
                    scores[i] += (c + 1);
                }
            }
            if (i == 25) {
                for (int i = 0; i < 26; i++) {
                    if (runners[i] > 0) {
                        for (int c = i + 1; c < 26; c++) {
                            if (runners[c] > 0) {
                                if (runners[i] != runners[c]) {
                                    cout << "Invalid Input try again: ";
                                    cin >> race;
                                }
                            }
                        }
                    }
                }
            }
        }
    //Divide scores by runners to figure out overall score
    for (int i = 0; i < 26; i++) {
        scores[i] = scores[i] / runners[i];
    }
    //Prints teams and scores
    for (int i = -1; i < 26; i++) {
        for (int c = 0; c < 2; c++) {
            if (c == 0 && i == -1) cout << "Team ";
                if (c == 1 && i == -1) cout << "Scores\n";
                if (i >= 0 && c == 0 && scores[i] > 0) cout << 
                                                       (char)teams[i] 
                                                     <<   "    ";
                if (i >= 0 && c == 1 && scores[i] > 0) cout << scores[i];
            }
            if (scores[i] > 0) cout << endl;
        }
    //Prints out winning team
        cout << "Input uppercase letters indicating the outcome of a race:";
        cin >> race;
    }
    return 0;
}

任务是打印出比赛的结果。每个团队都由大写字母指定,我们假设用户只会输入正确的输入。我的问题是在while之后的第一个for循环中。每当用户输入一串字符时,每个字符必须出现相同的时间量。所以,如果我输入的AACC是正确的,但如果我输入的AACCB不正确。我的程序会说AACCB不正确,但有时它也会说AACC也不正确。如果我继续输入它并且它说不正确(对于AACC)然后我会再次输入它会告诉我它是正确的。什么可能是错的?

0 个答案:

没有答案