【问题标题】:The following code always give 'draw!' as output下面的代码总是给出'draw!'作为输出
【发布时间】:2016-12-20 08:24:45
【问题描述】:

我不明白为什么下面的代码总是打印“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 << "\n\n 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;
    }

【问题讨论】:

  • 链接失效,请阅读How to ask
  • edit 在您的问题中提供minimal reproducible example 在问题本身
  • 不是每个人都可以访问外部网站,链接可能会随着时间的推移而中断。
  • 将代码放入问题中。请记住,堆栈溢出不是论坛。问题的主要目的是帮助未来的读者解决同样的问题。如果您发布到外部网站,该链接可能会在一个月内失效,这对任何人都没有帮助。

标签: c++


【解决方案1】:

这段代码的问题在于if (choice2 == "SCISSORS")之类的代码 因为这是一个指针比较。详情请见this stack overflow post

我建议对这段代码进行现代化改造并使用std::string 而不是char [50],因为您不必担心这些字符串的内存,也不必担心字符串存储为数组这一事实。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-27
    相关资源
    最近更新 更多