簡體   English   中英

提出輔助函數C ++中的停止條件,

[英]Coming up with a stopping condition in a helper function C++,

我目前需要找出遞歸幫助器函數的停止條件,該條件在列表上只剩下一個數字或沒有數字可嘗試時停止。 該程序將猜測數字1-100,並逐步糾正自己,以便找出該人在想的數字。如果該人說得太高,我也對如何按順序獲得這些數字有一個好主意低,或者如果他們說程序正確的話。 但是,如果只剩下一個可能要猜的數字,或者用戶作弊並且沒有要嘗試的數字,我不知道如何停止該功能。 到目前為止,這是我遞歸函數的功能,我真的不知道從前面所述的當前問題開始,謝謝您的提前幫助。

#include<iostream>
#include<algorithm>
#include<string>
using namespace std;

void guessingGame(int size, int low)
{
string answer;
unsigned int median = (low + size) / 2;
cout << "Is your number " << median << " l , y , h? ";
cin >> answer;

if (answer == "l" || answer == "L")
{
    low = median;
    guessingGame(size, low);
}
if (answer == "h" || answer == "H")
{
    size = median;
    guessingGame(size, low);
}
if (answer == "y" || answer == "Y")
{
    cout << "Told ya i'd guess it!\n";
}

  while (answer != "h" && answer != "y" && answer != "l")  
{                                                             
    cout << "\nPlease enter a valid input: ";                              
    cin >> answer;                                      
    cin.clear();                                  
    cin.ignore(50, '\n');                                        
    guessingGame(size, low);                                 
}

您的代碼無法編譯,但我將其視為偽代碼並專門回答您的問題。

基本上,您的停止條件將是low等於size ,而您只剩下一個數字。 此時,您有兩個選擇:

  • 用戶將輸入“ y”,那么這是正確的猜測,您可以從函數中返回。
  • 用戶將輸入“ l”或“ h”。 在這種情況下,用戶在作弊,因為只剩下一個號碼,而不是正確的號碼。

我建議將對“ y”的檢查移到開頭,在其他兩個對“ h”和“ l”的檢查之前,然后編寫如下內容:

if (answer == "y" || answer == "Y")
{
    cout << "Told ya i'd guess it!\n";
}

else if (low == size)
{
    cout << "Not fair! You're cheating.\n";
   // exit the routine.
}

else if (answer == "l" || answer == "L")
{
    low = median;
    guessingGame(size, low);
}
else if (answer == "h" || answer == "H")
{
    size = median;
    guessingGame(size, low);
}

如果用戶不回答“ y”,而您只剩下一個數字,那么他們就在作弊。

同樣,您的代碼有問題,但這只是停止條件的一種想法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM