首页 > 解决方案 > 在 C++ 中的 if-else if- else 语句期间更改变量

问题描述

正如我确信这个问题很清楚,我是新手并且正在学习,我相信很多人会想知道为什么要问......因为我得到了剩下的部分,而不是这个。我正在使用 C++ 并试图制作一个自我猜测程序,该程序使用给我的算法。我已经以多种方式玩过这部分代码,到目前为止,我缩小了范围的一件事是它没有做什么,我想了解为什么以及如何修复它,因为我没有尝试过任何工作。我一直在玩的代码的基本版本是这样的:

// test_room.cpp : This file contains the 'main' function. Program execution 
//begins and ends there. This is where 
//I am going to test some code to understand my mistakes and how to fix 
//them. 
// 

#include "pch.h"
#include <iostream>
#include <cstdlib>
#include<ctime>

using namespace std;

 int main()
 {
char play = 'y';
while (play == 'y')
{
    int bad = 27;
    int a = 50;
    int b = 1;
    int good = ((a - b) / 2);
    int s = 0;


    cout << "\nBegin?";
    cin >> play;
    do
    {

        ++s;
        if (good > bad)
        {
            cout <<"\n" <<good;
            cout <<"\n" << s;
            --a;
        }
        else if (good < bad)
        {
            cout << "\n"<<good;
            cout <<"\n" << s;
            ++b;
        }
        else
        {
            cout << "good job";
        }
    } while (s < 50);
}
cout << "\nOK\n";
return 0;
}

我的问题是我尝试移动变量,我已经修复了大括号问题,我尝试使用 cin>>good>>a 或 b(取决于 >< ),到目前为止我无法操纵变量 a 或 b 来获取它要尝试猜测或找出数字 27,它所做的只是重复 24 50 次。我需要做什么才能根据算法更改 a 和 b 的值?

标签: c++variables

解决方案


好的和坏的在循环中永远不会改变,我真的不明白你算法的目的(它看起来像二进制搜索,但不是真的),但是如果你没有改变 if 条件在循环,则不会评估任何其他条件。


推荐阅读