c++ - 可以使用循环来收集多个变量吗?
问题描述
我想提示一个字符串变量(项目名称),然后提示一个双变量(成本)。我希望这样做 5 次,所以每次循环时,vales 都存储为不同的变量对。
需要让用户输入一个项目,然后输入它的价格,这样我就可以计算账单。不确定我是否可以为此创建一个循环,或者我需要以某种方式保持运行计数
int main()
{
int i;
string Item_1,Item_2,Item_3,Item_4,Item_5;
double Price_1,Price_2,Price_3,Price_4,Price_5 ;
while (i<6)
{
cout<<"Please enter item"<<endl;
cin>> Item_1>>Item_2>>Item_3>>Item_4>>Item_5>>endl;
cout<<"Please enter cost of " >> Item_1>>Item_2>>Item_3>>Item_4>>Item_5;
cin>>Price_1>>Price_2>>Price_3>>Price_4>>Price_5;
i=i++
}
return 0;
}
代码无法编译,但我希望它会要求我输入 5 个变量 5 次
解决方案
这是一个带有arrays
和for
循环的解决方案。
您可以在CPP Shell中尝试。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string Item[5];
double Price[5] ;
for(int i = 0; i < 5; i++)
{
cout<<"Please enter item"<<endl;
cin>> Item[i];
cout<<"Please enter cost of " << Item[i] << ":" << endl;
cin>>Price[i];
}
cout << "Items: ";
for(int i = 0; i < 5; i++)
{
cout << Item[i] << " ";
}
cout << endl << "Prices: ";
for(int i = 0; i < 5; i++)
{
cout << Price[i] << " ";
}
return 0;
}
推荐阅读
- reporting-services - 精确地在 SSRS 报告中移动像文本框这样的报告项?
- jenkins - 压缩詹金斯工作区文件夹中的所有文件
- mysql - MySQL order by before group by 不起作用
- java - 如何记录没有任何上下文的不安全请求?
- java - 在本地重现和解决 Android java.lang.unsatisfiedLinkError
- mysql - mysql 不适用于 AWS linux 实例?
- ios - 以编程方式添加“间距到最近的邻居”约束
- sql - 如何将子组转置或转置为单行?
- javascript - 节目带复选框 jquery
- elasticsearch - 如何在不影响性能、可扩展性的情况下获得更好的相关性并避免 Elasticsearch 的分片效应