我的程序应该要求输入成绩,然后输出这些成绩发生的次数。发生的次数由计数标记显示,我使用“*”作为计数标记。我当前的代码输出:
Enter number of grades:
4
Enter grades:
1
5
10
10
10
Histogram:
0
1 *
2
3
4
5 *
.
.
10 **
正如你所看到的,我要求的成绩数是4,但它需要5个输入,似乎不算第5。它还打印出两者之间的数字而不仅仅是分数。我想要实现的是
Enter number of grades:
4
Enter grades:
1
5
10
10
Histogram:
1 *
5 *
10 **
#include<iostream>
#include<vector>
#include<iomanip>
#include<algorithm>
using namespace std;
int main(){
int n;
int value = 0;
vector<int> grades;
cout<<"Enter number of grades:"<<endl;
cin >> n;
cout <<"Enter grades: "<<endl;
cin >> value;
for (int i=0; i<n; i++) // believe this condition is wrong, causing the input extra number. I've tried multiple variations and can not figure it out.
{
grades.push_back(value);
cin >> value;
}
int max = 0;
for(int i=0; i<grades.size(); i++)
{
if(grades[i] > max)
max = grades[i];
}
int* array= new int[max+1];
for(int i=0; i<grades.size(); i++)
{
array[grades[i]]++;
}
cout<<"The histogram is:"<<endl;
for(int i=0; i<=max; i++){
if(array[i]!=0)
char stuff;
std::string stuff(array[i], '*'); //pretty sure this is causing all the numbers to be printed, but I don't know another way to print the asterisk
cout<<i <<" "<<stuff<<std::endl;
}
return 0;
}
当包含打印星号的行时,为什么要打印所有数字?当我拿出用于打印星号的行时,它不再打印所有数字,但当然它也不会打印星号。
答案 0 :(得分:2)
这些行中的逻辑不正确。我们说n
是1
。
cin >> value; // Read the first number
for (int i=0; i<n; i++)
{
grades.push_back(value); // Push the first number
cin >> value; // Unnecessary input, which doesn't get used.
}
你需要:
for (int i=0; i<n; i++)
{
cin >> value;
grades.push_back(value);
}
答案 1 :(得分:0)
问题:
char stuff;
。此外,如果您修复#3,那么这将成为重新声明,并将导致编译器错误。固定代码:
#include <iostream>
#include <vector>
#include <iomanip>
#include <algorithm>
using namespace std;
int main() {
int n;
int value;
vector<int> grades;
cout << "Enter number of grades:" << endl;
cin >> n;
cout << "Enter grades: " << endl;
for (int i = 0; i < n; ++i) {
cin >> value;
grades.push_back(value);
} // end for
int max = 0;
for (int i = 0; i < grades.size(); ++i)
if (grades[i] > max)
max = grades[i];
int* count = new int[max+1]();
for (int i = 0; i < grades.size(); ++i)
++count[grades[i]];
cout << "The histogram is:" << endl;
for (int i = 0; i <= max; ++i) {
if (count[i] != 0) {
std::string stuff(count[i],'*');
cout << i << " " << stuff << std::endl;
} // end if
} // end for
return 0;
} // end main()
答案 2 :(得分:0)
cin >> value; // input:1
for (int i=0; i<n; i++)
{
grades.push_back(value);
cin >> value;// input:5,10,10,10, this is why you need to enter extra number(10),
// but the last number is never used
}
答案 3 :(得分:-1)
在for条件中添加=符号,即1&lt; = n 愿这解决你的问题。
for(int i = 0; i&lt; = n; i ++)