首页 > 解决方案 > 记住一个随机选择的值

问题描述

我正在创建一个用户与计算机对战的游戏。计算机的名称是从具有五个值的数组中选择的。我创建了一个介于 1 和 5 之间的随机数,然后使用它随机选择五个名称中的一个。我正在尝试将该名称保存为一个函数,以便我可以在整个游戏中继续重用该值。

到目前为止,我已经成功地让程序随机选择计算机的名称,但是当我调用该函数时,它会吐出数字而不是字符串。数字是相同的,所以我相信它正确地“记住”了这个值,但它没有以 ASCII 文本显示它......

这是我的代码: constants.h

#pragma once
#ifndef CONSTANTS_H

#include <string>

namespace constants {

    std::string computer[5] = { "Duotronics", "Hal", "Shirka", "Skynet", "Icarus" };
}

#endif // !CONSTANTS_H

主文件

#include <iostream>
#include <time.h>
#include <cstdlib>

#include "constants.h"

void opponent() {
    srand(time(NULL));
    int randomIndex = rand() % 5;

    std::string value = constants::computer[randomIndex];

    std::cout << value;
}

int main() {
    std::cout << "What is your name?\n";
    std::cin >> x; 

    srand(time(NULL));
    int randomIndex = rand() % 5;

    std::string value = constants::computer[randomIndex];

    std::cout << "Your opponent is the computer " << value << " she is hard to beat.\n";
    std::cout << "Good luck " << x << "!" << '\n';

    std::cout << opponent << '\n';
    std::cout << opponent << '\n';
    std::cout << opponent << '\n';

    return 0;
}

我得到以下返回:

Your opponent is the computer Duotronics she is hard to beat.
Good luck <user's name>!
00821659
00821659
00821659

当我调用valuemain 时,我得到了这个名字。但是,当我尝试在函数中使用相同的代码时,opponent我得到了数字......我试图将随机选择的计算机名称存储为一个函数,以便我可以在整个游戏中重复使用相同的名称。这个逻辑是必不可少的,因为游戏中还有其他值是随机选择的,我也需要游戏记住这些值。任何关于如何使这项工作的指示(也许是双关语?)将不胜感激。干杯!

标签: c++

解决方案


opponent返回函数的内存地址。您忘记了只调用该函数并执行其代码,而是在 main.js 中重新编写了代码。您的函数也应该返回名称。

这就是 main.cpp 的样子:

#include <iostream>
#include <time.h>
#include <cstdlib>

#include "constants.h"

std::string opponent() { // should return string, not void
    srand(time(NULL));
    int randomIndex = rand() % 5;

    std::string value = constants::computer[randomIndex];

    return value; // return the name
}

int main() {
    std::cout << "What is your name?\n";
    std::cin >> x; 

    // you do not need to re code the function here        

    std::string opponent_name = opponent(); // just call it !

    std::cout << "Your opponent is the computer " << opponent_name << " she is hard to beat.\n";
    std::cout << "Good luck " << x << "!" << '\n';

    std::cout << opponent_name << '\n';

    return 0;
}

输出 :

Your opponent is the computer Duotronics she is hard to beat.
Good luck <user's name>!
Duotronics 

推荐阅读