-1

我将如何在当前程序中使用向量;“在向量中使用美元面额 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;
}

基本上我的输出看起来像这样 =>“你所有账单的价值是 $”无论输入什么总和“”

我已经阅读了我的书并使用了 youtube,但仍然不能完全理解如何在此作业中使用向量;我是否也在 setw(5) 下正确使用“右对齐”?

4

2 回答 2

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";

dollarand相同denom,您就完成了。

于 2012-09-14T19:44:16.317 回答
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"
}

希望这会让你开始。

于 2012-09-14T19:50:21.960 回答