计数变量的初始值很高?

时间:2015-03-17 21:46:30

标签: c++

我想计算这个文件中的字母,grade.txt:

ABADACAFABCDFFFACDCCBBACBACCCBBAAAAADBACAFFBBCCDAABBFFAACCBBAACCCCBB

下面是代码:

#include <iostream> /* include header file to do input and output */
#include <fstream> /* include the library so you can read/write files */
#include <iomanip> /* include the library that allows formatting */
using namespace std; /* allow operations from standard library */

int main (void)
{
    int a,b,c,d,f = 0; //count of each grade
    char x; //stores the grade being read

    ofstream outfile;
    outfile.open("out.txt"); //output file


    ifstream infile;
    infile.open("grade.txt"); //read file w/ grades

    while(infile >> x) { //for every grade from file
                 switch(x) { 
                           case 'A': 
                                     a++; //increase the count for whichever grade is read
                                     break;

                           case 'B':
                                     b++;
                                     break;

                           case 'C':
                                     c++;
                                     break;

                           case 'D':
                                     d++;
                                     break;

                           case 'F':
                                     f++;
                                     break;

                           default:
                                   cout << "Invalid grade";
                           }         
                 }    

    outfile << "\nCounts of Each Letter Grade" << endl; //output results
    outfile << "A: " << a << " B: " << b << " C: " << c << " D: " << d << " F: " << f;
    cout << "A: " << a << " B: " << b << " C: " << c << " D: " << d << " F: " << f;

    system ("pause"); /* console window "wait"¦ */
    return 0;
} /* end of main function */

我的输出如下:

Counts of Each Letter Grade
A: 169 B: 2686848 C: 18 D: 5 F: 8

我无法为我的生活弄清楚为什么'a'和'b'有如此高的数量。当我调试时,它们似乎从非常高的值开始,然后正常运行。

3 个答案:

答案 0 :(得分:4)

该行

int a,b,c,d,f = 0; 

相当于

int a; 
int b; 
int c; 
int d; 
int f = 0; 

换句话说,abcd未初始化。

您可以使用

修复它
int a = 0, b = 0, c = 0, d = 0, f = 0; 

int a = 0; 
int b = 0; 
int c = 0; 
int d = 0; 
int f = 0; 

答案 1 :(得分:3)

当你这样做时

 int a,b,c,d,f = 0

您只需将 f 设置为 0 。其他的未初始化为0。

你可以一个一个地做

int a = 0;
int b = 0;

etc.

或类似

 int a,b,c,d,f;

 a = b = c = d = f = 0;

int a = 0, b = 0, c = 0, d = 0, f = 0;

答案 2 :(得分:2)

如果您希望变量具有已知的“初始”值,则需要初始化变量。我看到您使用f初始化0,您需要对其他计算变量执行相同操作。

int a = 0, b = 0, c = 0, d = 0, f = 0; //count of each grade