【问题标题】:How can I store the random numbers outputed by my funtion?如何存储我的函数输入的随机数?
【发布时间】:2022-06-28 23:23:50
【问题描述】:

目前我正在尝试将我的手牌和命中牌的数字相加,问题是我为我的随机数生成器创建了一个函数,以便我可以继续在我的骰子游戏和二十一点游戏中调用它,我通常会将数字生成器添加到变量中并每天调用它,但我将它变成了一个函数。我还是 C++ 新手。

`

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

void RandomNumber() {
    
    cout << (rand() % 10 )+ 1;
}
void blackjack(int total) {
    int startstakes = 15;
    int stakes;
    int hand;
    

    cout << "Welcome to the Blackjack(21) table\n" << "How much are you adding to your initial 15 chip stake - ";

    cin >> stakes;

    cout << "New stake - " << stakes + 15 << " remaining chips - " << total - (stakes + 15) << endl;

    cout << "Here is your hand - ";
    
    RandomNumber(); cout << " and "; RandomNumber();

    cout << "Hit me cards: 0 - 0 - 0\n" << "Total = ";






    system("pause>0");
}

int main()
{

    int total=0;
    int choice;
    
    srand((unsigned)time(NULL));

    cout << "Welcome to Royal Casino!!!, How much money do you wish to convert? ";

    cin >> total;

    cout << "Excelent you currently have " << total << " Chips.\n" << "Let's Begin!\n\n" << "We have to tables available today\n";

    cout << "1) Blackjack (21)\n" << "2) Dice\n" << "Both have an entry fee of 15 Chips\n" << "Select a table - ";

    cin >> choice;

    if (choice == 1) {
        blackjack(total);
    }

    if (choice == 2){
        dice();
    }

    system("pause");
}`

【问题讨论】:

  • 考虑修改你的函数以返回一个数字而不是打印它。

标签: c++


【解决方案1】:

所以问题是您应该返回该值而不是打印它。像这样(注意返回类型已经从void变成int

int RandomNumber() {
    return (rand() % 10) + 1;
}

返回值的函数比打印值的函数灵活得多。

现在您可以像使用变量一样使用函数调用RandomNumber()。例如

cout << RandomNumber() << " and " << RandomNumber();

int var = RandomNumber();

【讨论】:

  • 这看起来应该是评论而不是答案
猜你喜欢
  • 1970-01-01
  • 2022-11-15
  • 2016-06-05
  • 2018-09-26
  • 1970-01-01
  • 1970-01-01
  • 2018-05-14
  • 1970-01-01
  • 2020-12-10
相关资源
最近更新 更多