c++ - 记住一个随机选择的值
问题描述
我正在创建一个用户与计算机对战的游戏。计算机的名称是从具有五个值的数组中选择的。我创建了一个介于 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
当我调用value
main 时,我得到了这个名字。但是,当我尝试在函数中使用相同的代码时,opponent
我得到了数字......我试图将随机选择的计算机名称存储为一个函数,以便我可以在整个游戏中重复使用相同的名称。这个逻辑是必不可少的,因为游戏中还有其他值是随机选择的,我也需要游戏记住这些值。任何关于如何使这项工作的指示(也许是双关语?)将不胜感激。干杯!
解决方案
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
推荐阅读
- amazon-web-services - Amazon Rekognition:如何批量比较一张图像和多张图像的人脸?
- javascript - 缩小失败。包含模板文字时返回未缩小的内容
- c# - 使用 C# 使用 SSL 的 IISCreation 的任何示例示例?
- python - PyQt5 带有文本对齐的垂直选项卡
- c# - WPF 树视图。列表和文本框的双向数据绑定。如何在列表中查找元素?
- flutter - Flutter 布局建议
- kubernetes - TLSOption CipherSuites 不适用于 Istio Ingress Gateway
- java - 为什么这个 Java switch 语句默认调用方法而不是中断?编辑:为每种情况添加了中断,问题仍然存在
- python - Matplotlib Fill_between 不使用两条曲线和“位置”条件
- opengl - OpenGL 纹理扭曲不正确