Loop接受第一组输入,然后重用该值

时间:2014-11-28 13:51:36

标签: c++ loops io codeblocks

我目前正在学校学习C ++,我们的一个项目是创建一个计算预算的程序。当我运行我的程序时,接受项目成本输入的循环将接受一次输入,然后在每次循环时重用该值。我已经在网上搜索了一个解决方案,我的老师和我一样困惑。可能是Codeblocks存在问题,但我已经尝试使用不同的编辑器。如果有人知道如何解决它,那就太好了。

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    //Declares variables
    float itemCount = 0;
    float taxPercent = 0;
    float itemCost = 0;
    bool taxable = true;
    float totalTaxable = 0;
    float totalNontaxable = 0;
    float total = 0;

    //Receive user input
    cout << "How many items to you have to buy: ";
    cin >> itemCount;
    cout << "\nWhat is the tax percentage (do not include the % sign): ";
    cin >> taxPercent;

    //This code runs once for every item
    while (itemCount > 0){

        //Receive the remaining user input
        cout << "\nWhat is the cost of the item: ";
        cin >> itemCost;

        cout << "\nIs the item taxable (Please use either true or false): ";
        cin >> taxable;

        //Adds the item cost to either the taxable or nontaxable variables
        if (taxable == true){
            totalTaxable += itemCost;
            cout << "true";
        }  else{
            totalNontaxable += itemCost;
            cout <<"false";
        }

        itemCount -= 1;
    }
    total = (totalTaxable * (1 + (taxPercent / 100))) + totalNontaxable;
    cout << "\n--------------------------------------------------\n";
    cout << "You must earn $";
    cout << total;
    cout << " to meet this budget\n\n";
}

1 个答案:

答案 0 :(得分:1)

如评论中所述,你不能在布尔上使用cin。来自doc:

  

标准输入流是由环境确定的字符源。

所以这是你的固定代码(接受Y而不接受其他任何内容):

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    //Declares variables
    float itemCount = 0;
    float taxPercent = 0;
    float itemCost = 0;
    char taxable = '';
    float totalTaxable = 0;
    float totalNontaxable = 0;
    float total = 0;

    //Receive user input
    cout << "How many items to you have to buy: ";
    cin >> itemCount;
    cout << "\nWhat is the tax percentage (do not include the % sign): ";
    cin >> taxPercent;

    //This code runs once for every item
    while (itemCount > 0){

        //Receive the remaining user input
        cout << "\nWhat is the cost of the item: ";
        cin >> itemCost;

        cout << "\nIs the item taxable (Please use Y for Yes): ";
        cin >> taxable;

        //Adds the item cost to either the taxable or nontaxable variables
        if (taxable == 'Y'){
            totalTaxable += itemCost;
            cout << "true";
        }  else{
            totalNontaxable += itemCost;
            cout <<"false";
        }

        itemCount -= 1;
    }
    total = (totalTaxable * (1 + (taxPercent / 100))) + totalNontaxable;
    cout << "\n--------------------------------------------------\n";
    cout << "You must earn $";
    cout << total;
    cout << " to meet this budget\n\n";
}