无法计算方程,总是给出零

时间:2012-10-14 09:28:48

标签: c++ equation

我错过了什么吗?变量percentage_总是等于0.我检查了nTimes和winnings,它们给出正确的输入值。即使我测试出一个简单的等式,例如percentage_ = 1 + 1,百分比_也会给出0.有人可以帮忙吗?

    #pragma once
    #include <iostream>
    #include <string>
    #include <cstdlib>
    #include <iomanip>

    using namespace std;


    class GuessMachine
    {
    private:
        int nTimes;
        int winnings;
        string nM[6];

    public:
        GuessMachine();
        void displayPrizes();
        void displayMenu();
        int getInput();
        void checkNumber();
        void checkPrize();
    };



    void GuessMachine::checkPrize()
    {
        MagicNumber mn;
        int prize_=mn.generateNumber();
        float percentage_;

        percentage_ = float (winnings/nTimes*100); //<--On this line percentage is always 0 no matter what winnings and nTimes are
        cout<<"Percentage is "<<percentage_<<endl; 

        if(percentage_ >= 50)
        {
            cout<<"You have scored "<<percentage_<<"% and won "<<nM[prize_];
        }
        else
        {
            cout<<"You have scored "<<percentage_<<"%. You lose!!";
        }

        cin.ignore();
        cin.ignore();
    }

2 个答案:

答案 0 :(得分:1)

尝试

float (winnings) /nTimes*100

代替。

您的版本仍会将int - 0转换为浮点数。

如果/的一个操作数是浮点数,它将起作用。

答案 1 :(得分:0)

更改

percentage_ = float (winnings/nTimes*100);

 percentage_ = (float(winnings))/nTimes*100;

因为您需要将1个数字更改为float以使该部门处理浮点数。