【发布时间】:2015-09-06 01:02:05
【问题描述】:
似乎我总是来这里问愚蠢的问题,但它就是这样。截至目前,我正在参加我的第一门 compsci 课程,我们正在学习 c++。我之前对 c 有过非常基本的介绍,所以我想我会超越我目前的任务。现在我这样做只是为了炫耀,我觉得如果我不练习我以前的概念,它们最终会褪色。无论如何,解决问题!我应该编写一些代码,允许用户输入他们的姓名首字母,并进行一系列考试。现在这应该完成三件事:平均考试,打印输入的考试,并打印出他们的姓名首字母。嗯,本来很简单的任务,被你搞得一团糟。
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
string uInitials;
float avgExam = 0, tExam = 0;
int aExams[10] = {'0'};
int i, nExam = 0, cExam;
cout << "Enter your three initials!";
cin >> uInitials;
do
{
cout << "Enter your exam(s) to be averaged. Enter 0 when complete!\n";
cin >> cExam;
aExams[nExam] = cExam; //I used this before nExam was incremented, in order to get nExam while it was '0' That way the first exam score would be properly saved in the first space
nExam++;
tExam += cExam; //This is just to add all the exams up to later calculate the average
}
while(cExam != 0);
avgExam = tExam/(nExam - 1); //subtracted '1' from nExams to remove the sentinel value from calculations.
cout << "The average for initials: " << uInitials << " is: " << avgExam << endl;
cout << "This average was obtained using the following scores that were entered: \n";
for(i = 0; i < (nExam+1); i++)
{
cout << aExams[i] << endl; //Used a for loop to prevent redundancy
}
return 0;
}
前面是我的代码,问题是当我打印出输入的考试列表时,我得到了输出错误,它添加了两个“0”。此外,我觉得我让整个 do{}while() 循环变得非常笨拙,所以我也想改进它。如果有人能帮助这个可怜的、无知的初学者,我将不胜感激。感谢您的宝贵时间!
【问题讨论】:
-
无保护以防止超出输入缓冲区的末尾
-
您使用的是 IDE 吗?如果有,是哪一个?
-
我正在使用 code::blocks!这是我最舒服的一个。
-
Code::blocks 是 GDB 调试器的前端。你会有一点学习曲线,但从长远来看,没有什么比弄清楚如何调试自己的代码更有用的了。如果您单步执行代码,您当前的问题很容易发现。
-
不要使用 C 风格的数组。使用
std::array或std::vector,它们是由好的调试器检查的边界,并且会检测到许多错误。 Vector 还允许您根据需要调整大小,而不是选择任意数字,例如 10,如果需要超过 10 个元素,它将中断。= {'0'};不会将int的数组设置为全 0(检查您的调试器)。请改用= {};。 (对于自动为 0 的向量不需要)
标签: c++ arrays codeblocks average