首页 > 解决方案 > 可以使用循环来收集多个变量吗?

问题描述

我想提示一个字符串变量(项目名称),然后提示一个双变量(成本)。我希望这样做 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 次

标签: c++

解决方案


这是一个带有arraysfor循环的解决方案。

您可以在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;
}

推荐阅读