【发布时间】:2022-11-15 11:04:19
【问题描述】:
void addNumbers(vector<double> &vec) {
double add_num {};
cout << "Enter an integer to add: ";
cin >> add_num;
vec.push_back(add_num);
cout << add_num << " added" << endl;
}
向量是空的,我只希望人们能够向其中添加数字,每当他们尝试其他任何操作时,它都会显示“无效数字”。
完整的代码在下面,目前它只是一遍又一遍地循环说“0.00 added”如果我在大声笑中放了数字以外的东西
#include <iostream>
#include <vector>
#include <bits/stdc++.h>
#include <iomanip>
#include <cctype>
using namespace std;
char choice {};
char menu();
void print(vector<double>);
void mean(vector<double>);
void addNumbers(vector<double> &vec);
void smallest(vector<double>);
void largest(vector<double>);
char menu() {
cout << "\nP - Print numbers" << endl;
cout << "A - Add a number" << endl;
cout << "M - Display mean of the numbers" << endl;
cout << "S - Display the smallest number" << endl;
cout << "L - Display the largest number" << endl;
cout << "Q - Quit" << endl;
cout << "\nEnter your choice: ";
cin >> choice;
choice = toupper(choice);
return choice;
}
void print(vector<double> vec) {
if (vec.size() != 0) {
cout << "[ ";
for (auto i : vec) {
cout << i << " ";
}
cout << "]";
}
else {
cout << "[] - the list is empty" << endl;
}
}
void addNumbers(vector<double> &vec) {
double add_num {};
cout << "Enter an integer to add: ";
cin >> add_num;
vec.push_back(add_num);
cout << add_num << " added" << endl;
}
void mean(vector<double> vec) {
if (vec.size() != 0) {
double result {};
for (auto i : vec) {
result += i;
}
cout << "The mean is " << result / vec.size() << endl;
}
else {
cout << "Unable to calculate the mean - no data" << endl;
}
}
void smallest(vector<double> vec) {
if (vec.size() != 0) {
cout << "The smallest number is " << *min_element(vec.begin(), vec.end()) << endl;
}
else {
cout << "Unable to determine the smallest number - list is empty" << endl;
}
}
void largest(vector<double> vec) {
if (vec.size() != 0) {
cout << "The largest number is " << *max_element(vec.begin(), vec.end()) << endl;
}
else {
cout << "Unable to determine the largest number - list is empty" << endl;
}
}
int main() {
vector<double> vec {};
bool done {true};
cout << fixed << setprecision(2);
do {
menu();
switch (choice) {
case 'P':
print(vec);
break;
case 'A': {
addNumbers(vec);
break;
}
case 'M': {
mean(vec);
break;
}
case 'S': {
smallest(vec);
break;
}
case 'L':
largest(vec);
break;
case 'Q':
cout << "Goodbye" << endl;
done = false;
break;
default:
cout << "Unknown selection, please try again" << endl;
}
} while (done == true);
return 0;
}
【问题讨论】:
-
cin >> add_num如果他们键入无法转换为双精度值(如“dog”)的内容,将返回 false。这个答案应该有帮助:https://stackoverflow.com/a/43080091/487892 -
您不能将变量限制为从
std::cin获取它们的值。变量从初始化、赋值、复制或移动中获取它们的值。您将不得不修改编译器或创建一个新的语言关键字来限制变量只能从std::cin获取它们的值。 -
这些包含语句在很大程度上表明您不知道自己在写什么。随着程序变得越来越复杂,这很快就会出现问题。前向声明函数,然后立即执行它们也是如此。
-
由于您将所有
std标签、关键字和名称包含在全局命名空间中,因此请注意您的变量和函数名称。最好不要使用using namespace std;。 -
@sweenish:对不起,我回答了 OP 的标题问题。我已经更新了我的评论。
标签: c++