Loops 无法创建函数以确保为int,发生无限循环,平均函数保持加法
所以我的问题是,我试图使用一个函数来确保int加上_值,但它不起作用。如果我输入一个字母,它就会开始一个无限循环。而且,如果我再次按下M,我的平均函数会不断增加,我不知道为什么。对不起,如果这是一个非常简单的问题,我真的是编程新手。我已经搜索了一些方法来确保它是一个int,但是它没有向向量添加值Loops 无法创建函数以确保为int,发生无限循环,平均函数保持加法,loops,vector,printing,switch-statement,Loops,Vector,Printing,Switch Statement,所以我的问题是,我试图使用一个函数来确保int加上_值,但它不起作用。如果我输入一个字母,它就会开始一个无限循环。而且,如果我再次按下M,我的平均函数会不断增加,我不知道为什么。对不起,如果这是一个非常简单的问题,我真的是编程新手。我已经搜索了一些方法来确保它是一个int,但是它没有向向量添加值 #include <iostream> #include <vector> #include <algorithm> #include <limits>
#include <iostream>
#include <vector>
#include <algorithm>
#include <limits>
using namespace std;
int main()
{
//variables must stay outside the loop otherwise
//every iteration it will replaced by a new value
bool control_end = false;
vector<int> vec{};
int mean{0};
int running_sum{0};
bool is_numb{0};
//int min_value{0};
do
{
cout << "Please enter your desired function within the menu: " << endl;
cout << endl;
cout << "P--Print list of numbers" << endl;
cout << "A--Add a number"<< endl;
cout << "M--Display mean of the vector"<< endl;
cout << "S--Display the smallest number"<< endl;
cout << "L--Display the largest number"<< endl;
cout << "Q--Quit "<< endl;
cout << endl;
cout << "Enter your choice: ";
cout << endl;
char letra{};
cin >> letra;
switch(letra)
{
case 'A':
case 'a':
{
cout << "Please enter the value (integer) to be added to vector: ";
int value_add;
cin >> value_add;
cout << endl;
vec.push_back(value_add);
cout << "Value added: " << value_add << endl;
// create a function to ensure that the value is an integer
if(isdigit(value_add))
{
vec.push_back(value_add);
cout << "Value added: " << value_add << endl;
}
else
{
cout << "Invalid value."<< endl;
cout << endl;
}
break;
}
case 'p':
case 'P':
{
if (vec.size()>0)
{
cout << "This is your vector: \n";
//for (unsigned int i=0 ;i < vec.size(); i++)
//cout << "{"<< vec[i] << "}" << " ";
//cout << endl;
for (auto print: vec)
cout << print << " ";
cout << endl;
}
else
{
cout << "The vector is empty." << endl;
cout << endl;
}
break;
}
case 'm':
case 'M':
{
for (auto mean_func:vec)
{ // it continues to keep adding and calculating the mean
// cout << mean_func << endl;
running_sum += mean_func;
// cout << running_sum << endl;
mean = running_sum/vec.size();
//cout << vec.size() << endl;
}
cout << "The mean is: " << mean << " ";
cout << endl;
//cout << mean << endl;
break;
}
case 's':
case 'S':
cout << endl;
cout << "Min Element = " << *min_element(vec.begin(), vec.end());
cout << endl;
break;
case 'L':
case 'l':
cout << endl;
cout << "Max Element = " << *max_element(vec.begin(), vec.end());
cout << endl;
break;
case 'q':
case 'Q':
cout << "Thank you for using the program" << endl;
control_end = true;
break;
default:
cout << "Invalid char. " << endl;
cout << endl;
break;
}
}
while (control_end !=true);
return 0;
}
#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{
//否则变量必须留在循环之外
//每次迭代它都将被一个新值替换
bool control_end=假;
向量向量{};
int平均值{0};
int运行_sum{0};
布尔是{0};
//int min_值{0};
做
{
库特