这个程序使用数组来保持9局的棒球比分。它计算每个局的高得分队伍和比赛的总冠军。
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
const int n = 9;
void PrintInput(char[], int[], char[], int[]);
void InningWinner(char[], int[], char[], int[]);
int main()
{
int scores1[n];
int scores2[n];
char team1[n], team2[n];
PrintInput(team1,scores1,team2,scores2);
InningWinner(team1,scores1,team2,scores2);
return 0;
}
void PrintInput(char t1[], int s1[], char t2[], int s2[])
{
cout << "\n********************************************************************\n";
cout << "Team 1: " << t1 << " ";
for (int i = 0; i < n; i++){
cout << setw(5) << s1[i];
}
cout << "\n";
cout << "Team 2: " << t2 << " ";
for (int i = 0; i < n; i++){
cout << setw(5) << s2[i];
}
}
void InningWinner(char t1[], int s1[], char t2[], int s2[])
{
for (int i = 0; i < n; i++){
if (s1[i] > s2[i])
cout << endl << t1 << " Wins Inning " << i + 1 << endl;
else if (s2[i] > s1[i])
cout << endl << t2 << " Wins Inning " << i + 1 << endl;
else if (s1[i] == s2[i])
cout << endl << " Inning " << i+1 << " ends in a TIE" << endl;
}
}
答案 0 :(得分:2)
在没有显式初始化的情况下使用所有数组,这将产生未定义的结果。
答案 1 :(得分:0)
在打印或进行计算之前,您需要将值读入score1 / 2和teams1 / 2。您可以从std :: cin中读取:
std::cout << "Enter " << n << " scores then press enter: ";
int num_scores_read;
for (num_scores_read = 0; std::cin >> scores1[num_scores_read]; ++num_scores_read)
;
if (!std::cin || num_scores_read < n)
{
std::cerr << "error reading score number " << num_scores_read << '\n';
exit(EXIT_FAILURE);
}
(类似于得分2等)
或者,您可以从文件中读取它们(与上面类似,但请使用
#include <fstream>
std::ifstream file(filename);
...as above but use "file" in place of "std::cin"...
或者,只需在程序中对一些示例值进行硬编码即可开始使用:
int scores1[n] = { 1, 3, 5, 1, 3, 5, 4, 5, 3 };