计数变量具有较高的初始值
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;
换句话说,a
、b
、c
和d
未初始化。
你可以使用来修复它
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
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 将数组的地址分配给变量并删除
- 为"adjacent"变量赋值时出现问题
- enum是C++中的宏变量还是整数变量
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 用C++中的一个变量定义一个常量
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 你能重载对象变量名本身返回的内容吗
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 尝试通过多个向量访问变量时,向量下标超出范围
- 试图让变量检查数组中的某些内容
- Cpp-Tuple使用带有变量的get
- 将包含C样式数组的对象初始化为成员变量(C++)
- 当vector是tje全局变量时,c++中vector的内存管理
- 通过多个头文件使用常量变量
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 执行函数时导致崩溃的变量
- 变量没有改变?通过向量的函数调用