我如何在当前程序中使用向量; “使用美元面额1,2,5, 向量中的10,20,50和100。“
int main()
{
int i, dollar[7] = {0}, denom[7] = {1,2,5,10,20,50,100}, total = 0;
string names[7] = {
"1-Dollar bill",
"2-Dollar bill",
"5-Dollar bill",
"10-Dollar bill",
"20-Dollar bill",
"50-Dollar bill",
"100-Dollar bill"
};
for(i = 0; i < 7; i++)
{
cout << "How many " << setw(5) << names[i];
if(i == 0)
cout << "s";
else
cout << "s";
cout << " do you have? ";
cin >> dollar[i];
}
for(i = 0; i < 7; i++)
{
cout << "You have" << setw(5) << dollar[i] << " " << names[i] << right;
if(i == 0)
if(dollar[i] == 1)
cout << " ";
else
cout << "s ";
else if(dollar[i] != 1)
cout << "s ";
total += dollar[i] * denom[i];
cout << endl;
}
cout << "The value of all your bills is $" << total << endl;
return 0;
}
基本上我的输出看起来像这样=&gt; “所有账单的价值都是$”无论输入金额是多少“”
我已经阅读了我的书并使用了youtube,但仍然无法完全理解如何在此作业中使用向量;我也是在setw(5)下正确使用“正确辩解”吗?
答案 0 :(得分:2)
它可以简单得多,替换
string names[7]= {
"1-Dollar bill",
"2-Dollar bill",
"5-Dollar bill",
"10-Dollar bill",
"20-Dollar bill",
"50-Dollar bill",
"100-Dollar bill"
};
与
vector<string> names(7); /* note round brackets not square brackets */
names[0] = "1-Dollar bill";
names[1] = "2-Dollar bill";
names[2] = "5-Dollar bill";
names[3] = "10-Dollar bill";
names[4] = "20-Dollar bill";
names[5] = "50-Dollar bill";
names[6] = "100-Dollar bill";
与dollar
和denom
相同,您就完成了。
答案 1 :(得分:0)
int main()
{
std::vector<int>dollar; //This makes an empty vector of ints
std::vector<int>denom; //so does this.
int total = 0;
std::vector<std::string> names; //this makes an empty vector of strings.
names.push_back("1-Dollar bill"); //push_back means add to the end of the vector
names.push_back("2-Dollar bill");
names.push_back("5-Dollar bill");
names.push_back("10-Dollar bill");
names.push_back("20-Dollar bill");
names.push_back("50-Dollar bill");
names.push_back("100-Dollar bill");
cout << names[0]; //This prints "1-Dollar bill"
}
希望这会让你开始。