记住一个随机选择的值

  • 本文关键字:随机 选择 一个 c++
  • 更新时间 :
  • 英文 :


我正在创建一个用户与电脑对抗的游戏。计算机的名称是从包含五个值的数组中选择的。我在1 &5,然后用它从五个名字中随机选择一个。我试图将该名称保存为一个函数,以便我可以在整个游戏中继续重用该值。

到目前为止,我已经成功地让程序随机为计算机选择一个名称,但是当我调用该函数时,它会吐出数字而不是字符串。虽然数字是一样的,所以我相信这是"回忆"。 下面是我的代码:constants.h
#pragma once
#ifndef CONSTANTS_H
#include <string>
namespace constants {
std::string computer[5] = { "Duotronics", "Hal", "Shirka", "Skynet", "Icarus" };
}
#endif // !CONSTANTS_H

main.cpp

#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

当我在main中调用value时,我得到了名称。然而,当我试图在函数opponent中使用相同的代码时,我得到了数字……我试图将随机选择的计算机名称存储为函数,以便我可以在整个游戏中重复使用相同的名称。这种逻辑很重要,因为游戏中还有其他随机选择的值,我也需要游戏记住这些值。任何指针(双关语可能?)如何得到这个工作将非常感激。干杯!

opponent返回函数的内存地址。你忘了调用这个函数并执行它的代码,你在你的main中重新编码了它。此外,你的函数应该返回名称。

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 

调用opponent()将不会记住randomIndex。为此,这里我使用static版本。如果没有适当的锁,不要在多线程中使用这个

std::string opponent() {
static int randomIndex = -1;
if (randomIndex == -1) {
srand(time(NULL));
randomIndex = rand() % 5;
}
std::string value = constants::computer[randomIndex];
return 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;
}

最新更新