以下代码始终提供'draw!'作为输出
The following code always give 'draw!' as output
我不明白为什么下面的代码总是打印'draw!你能帮我弄明白吗?
#include <iostream.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
void main()
{
clrscr();
int choice1;
char choice2[50];
int compare(const char*, const char*); //prototype
char s[100];
cout << "nn WELCOME TO STONE PAPER SCISSORS " << endl
<< endl;
cout << " enter your choice" << endl;
cout << "n 1:SCISSORS n";
cout << "n 2:ROCK n";
cout << "n 3:PAPER n";
cout << "enter choice number";
cin >> choice1;
if (choice1 == 2) {
cout << "you have entered Stone!";
strcpy(s, "ROCK");
}
if (choice1 == 1) {
cout << "you have entered scissors";
strcpy(s, "SCISSORS");
}
if (choice1 == 3) {
strcpy(s, "PAPER");
cout << "you have entered paper";
}
randomize();
float point = 2;
float compchoice;
compchoice = random(point);
if (compchoice < 0.37) {
strcpy(choice2, "ROCK");
}
else if (compchoice < 0.64) {
strcpy(choice2, "PAPER");
}
else {
strcpy(choice2, "SCISSORS");
}
cout << endl;
cout << "User Choice=" << s << endl;
cout << "Computer Choice=" << choice2 << endl;
cout << s << "t"
<< "VS"
<< "t" << choice2 << "="
<< " ";
int p = compare(s, choice2);
if (p == 1) {
cout << "computer wins";
if (p == 0)
cout << "user wins";
if (p == -1)
cout << "draw!";
getch();
}
int compare(const char* s, const char* choice2)
{
if (s == "SCISSORS") {
if (choice2 == "ROCK")
return 1;
else
return 0;
}
else if (s == "ROCK") {
if (choice2 == "SCISSORS")
return 0;
else
return 1;
}
else if (s == "PAPER") {
if (choice2 == "SCISSORS")
return 1;
else
return 0;
}
else
return -1;
}
这段代码中的问题存在于类似if (choice2 == "SCISSORS")
的代码中因为这是一个指针比较。
我建议现代化这段代码并使用std::string
而不是char [50]
,因为您不必担心这些字符串的内存,也不必担心字符串被存储为数组的事实。
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 请解释"函数1(p1,p2,p3);"的输出
- C++:将控制台输出存储在宏中更好吗
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 为什么我的代码在输出中增加了93天
- 如何从void函数输出字符串
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- AES加密到解密未正确输出
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- C++格式化输出问题
- 将值从二维数组输出到文本文件
- 集合上的输出迭代器:assign和increment迭代器
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 为什么rk4.do_step不输出C++中的初始条件
- 输出没有重复元素的动态数组(收缩数组)C++
- 以下代码始终提供'draw!'作为输出