我错过了什么?变量percent_始终等于0。我已经检查了nTimes和奖金,它们输入的值正确。即使我测试了一个简单的方程式(例如percent_ = 1 + 1),percent_也会给出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();
    }

最佳答案

尝试

float (winnings) /nTimes*100


代替。

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

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

关于c++ - 无法计算方程式,始终为零,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12880912/

10-13 03:54