提问人:Joseph Hill 提问时间:5/5/2023 更新时间:5/5/2023 访问量:67
如何获得CIN数组的总和?
how to get the sum of a cin array?
问:
我仍然是 C++ 的新手,我正在创建一个预算项目。
我正在努力获取数组所有值的总和,该数组是由用户输入创建的。问题是当我运行它时,它没有给出正确的答案。我正在尝试一步一步地做到这一点,所以当被问及是否要继续时,我只通过输入“否”来测试它。 我做了笔记,这样就不会有混淆,我一直被困在这个上面,可以使用帮助。另外,如果您有任何其他提示和技巧可以使这个清洁工随时告诉我,谢谢!
usersMonthlyExpenses[] 是数组
numsize 是大小
#include <iostream>
using namespace std;
#include <locale>
#include <string>
//This function gets the users monthly expenses information
void getInfo(int usersMonthlyExpenses[], int numsize){
//initialize
cout<<"please input your expenses. Type done when finished."<<endl;
string done = "";
int sum = 0;
// this while statement loops the users input until a certain amount
for(int i = 0; i <= numsize; i++){
cin>>usersMonthlyExpenses[i];
cin>>done;
sum = sum + usersMonthlyExpenses[i];
i++;
//this if statment is for when the user has reached that certain number of input it ask if they wish to continue
if (i >= numsize){
//initialize
string yes = "yes";
string no = "no";
string choice;
cout <<"would you like to add more? please type yes or no: ";
cin >> choice;
if(choice == yes){
getInfo(usersMonthlyExpenses, numsize);
}else if(choice == no){
// this is where the problem is
for(int i = 0; i < numsize; i++){
sum+=usersMonthlyExpenses[i];
}
cout<<sum
break;
} else{
cout<< "please type yes or no: ";
cin>>choice;
}
}
// if user types done then add up their expenses
if(done == "done"){
cout<< "This is your total monthly expenses: "<< sum;
break;
}
}
}
int main(){
//declaring functions and variables
// int usersMonthlyIncome;
// int budgetSelection;
// int x;
// int fiftyRule(int usersMonthlyIncome);
// some variables to get this function initialized
int numsize = 5;
int costNameSize = 5;
int usersMonthlyExpenses[numsize] = {};
int usersCostName[costNameSize];
getInfo(usersMonthlyExpenses, numsize);
return 0;
}
我尝试为它创建一个函数,只是在参数中传递数组,但这不起作用,我用几种不同的方式重写了它,看看什么有效,但无论我做什么,它都没有给出正确的答案。
答: 暂无答案
评论
for(int i = 0; i <= numsize; i++)
i++;
<=
sum
std::vector<int>
for (auto&& x : y)
std::vector
std::vector<>::push_back()