需要帮助从不同的功能输出内容(C++)

Need help outputting things from different functions (C++)

本文关键字:输出 C++ 功能 帮助      更新时间:2023-10-16

我对C++和编码相当陌生。我正在尝试制作一个基本的多项选择类型游戏进行练习,但我遇到了一个难题。

该程序也没有输出我想要的东西。这是代码:

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;
void sword(int damage);
void fists(int damage);
static int enemyHealth = 250;
int main() {
    srand(time(0));
    string SOF; //Abreveation for "Sword Or Fists"
    cout << "You will be fighting a mean bad guy. Are you using a sword, or your fists?n";
    while (SOF != "sword" && SOF != "fists"){
        cout << "Please enter your choice of either 'sword' or 'fists': ";
        cin >> SOF;
    }
    cout << "Okay! Time to fight! n";
    if (SOF == "fists") {
        void fists();
    }
    else if (SOF == "sword") {
        void sword();
    }
    else{ (NULL); }
    cout << "Congratulations! You have vanquished that foul beast!n";
    system("pause");
}
//This is for when the user chooses 'sword'
void sword(int damage = rand() % 100 + 50) {
    while (enemyHealth > 0){
        cout << "You deal " << damage << " damage with your sharp sword. n";
        enemyHealth -= damage;
    }
}
//This is for when the user chooses 'fists'
void fists(int damage = rand() % 10 + 4) {
    while (enemyHealth > 0){
        cout << "You deal " << damage << " damage with your womanly fists. n";
        enemyHealth -= damage;
    }
}

第一部分工作正常,但是当我输入"fists""sword"的选择时,输出是:

Okay! Time to fight!
Congratulations! You have vanquished that foul beast!

但我希望它输出用拳头或剑造成的伤害。

如果我能得到一些帮助,那就太神奇了。谢谢!

void fists();是一个声明,而不是一个调用,更改为fists();sword();

其他注意事项:

  • 默认参数在main之前在函数声明中声明(或者只是将整个函数移动到那里)
  • c++ 中的默认参数只计算一次,因此代码中的所有"命中"都是相同的
  • 局部变量名称通常不以大写形式命名,SOF看起来它是一个#define d 常量之类的。

调用函数,不要写void fists();,只是

fists();

(您拥有的是一个声明,在这里没有有用的效果,而不是调用。