计数变量具有较高的初始值

Counting variables have high initial values?

本文关键字:变量      更新时间:2023-10-16

我想计算这个文件中的字母,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"answers"b"的计数如此之高。当我调试时,它们似乎以极高的值启动,然后正常运行。

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; 

进行时

 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;

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

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