公式中没有把小数计算在内

The decimal is not taken into acount in the equation

本文关键字:小数 计算      更新时间:2023-10-16

我最近才开始学习C++,我计划主要制作游戏。很自然,我决定四处玩耍,看看我能做些什么

#include <iostream>
#include <ctime>
#include <cstdlib> 
using namespace std;
int main ()
{ 
    int HIT, DMG, HRT, ATK, DEF, EVS, EVS1, CRT, CRT1, CRT2, CRTMUL, CRTMUL1, BK, BKDMG;
    srand( time(0));
    HIT=rand()%100+1;
    cout<<"Please enter thier Evasion: ";
    cin >> EVS;
    EVS1 = 100 - EVS;
    if ( HIT < EVS1 ) {
        cout<<"Hit!";
        cout << 'n';
    }
    else if ( HIT > EVS1 ) {
        cout<<"Miss!";
        return 0;
    }
    cout<<"Please enter your Damage: ";
    cin >> DMG;
    cout<<"Please enter your Attack: ";
    cin >> ATK;
    cout<<"Please enter thier Defence: ";
    cin >> DEF;
    cout<<"Please enter your Crit Chance: ";
    cin >> CRT;
    cout<<"Please enter your Crit Multiplier: ";
    cin >> CRTMUL1;

    CRT1=rand()%100+1;
    CRT2 = 100 - CRT;
    if ( CRT1 < CRT2 ) {
        cout<<"You didnt crit.";
        cout << 'n';
    CRTMUL = 1;
    }
    else if ( CRT1 > CRT2 ) {
        cout<<"Crit!";
        cout << 'n';
        CRTMUL = CRTMUL1;
    }   

    // no matter what you input here,...
    cout<<"From where did you hit them? ";
    cout << 'n';
    cout<<"(1 for from the back, 2 for from the side, 3 for from the front).";
    cout << 'n';
    cin >> BK;
    // ...this area...
    if ( BK = 1 ) {
        BKDMG = 1.6;
    }
    else if ( BK = 2 ) {
        BKDMG = 1.3;
    }
    else if ( BK = 3 ) {
        BKDMG = 1;
    }
    // ... to this area wont work, in the equation below BKDMG is allways 1
    HRT =  ((((((ATK/5)/100)+1)*(DMG))-(((((ATK/5)/100)+1)*(DMG))/100)*(DEF/5))*BKDMG)*CRTMUL;
    cout<<"You hit for ";
    cout<<HRT;
    cout<<" damage!";
    return 0;
}

正如你在代码中看到的,无论你为BK输入什么,BKDMG似乎都会以1的结果出现。我相信这是因为四舍五入?如果不告诉我。

如果是,我该如何解决此问题?我想答案就在这里,但我不知道该搜索什么,因为我不知道问题出在哪里。根据我的理解,float可以帮助我吗?我不明白浮点是什么,因为这是我编码的第一件事。

您已经将BKDMG定义为int类型,这意味着它只能容纳整数。所以,是的,如果你给它分配一个实数值,它会把它四舍五入到下一个整数值。对于这个例子,使用doublefloat可能就足够了。

你的条件也是错误的:

if ( BK = 1 ) {
    BKDMG = 1.6;
}

因为'BK=1'是一个赋值,所以它总是将BK的值设置为1。上面的代码片段应该是:

if ( BK == 1 ) {
    BKDMG = 1.6;
}
if ( BK = 1 ) 

是一个典型的(初学者(错误。你不是在比较,你是在分配。

应该是

if ( BK == 1 ) 

甚至更好,

if ( 1 == BK) 

如果你把常数放在第一位,就不可能出错。