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

标签 c++ equation

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

最佳答案

尝试

float (winnings) /nTimes*100

相反。

您的版本仍将 int - 0 转换为 float。

如果 / 的一个操作数是一个 float ,它就可以工作。

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

相关文章:

c++ - 在单独的文件中未定义的枚举类成员

css - 为什么在等式中使用 0 时 css-calc() 不起作用?

C# 设置对象参数

c# - 如何将字符串 c# 方程转换为答案

Java 将表达式推导为表达式和方程

c# - 如何在 C# 中将数组放入结构中?

c++ - 获取当前桌面壁纸的路径

c++ - 确保给定图像与另一图像翻转

c++ - Windows网络包修改

python - 如何用Python解方程