0

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

2 回答 2

1

尝试

float (winnings) /nTimes*100

反而。

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

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

于 2012-10-14T09:31:27.880 回答
0

改变

percentage_ = float (winnings/nTimes*100);

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

因为您需要将 1 个数字更改为浮动,以便该部门在浮动上工作。

于 2012-10-14T09:33:27.783 回答