-1

好吧,我试图猜测最接近中奖号码的数字系列(忽略平局的可能性),让我们说中奖号码是 15。

我还想确保它不超过中奖号码。最后一个条件是,如果所有的猜测都太大,就不会有赢家。

假设数量如下:

12
9 
7
13
4
0

我希望程序选择 13 作为中奖号码。

这是我写的代码的片段:

corrrectGuess = 15
while(contestantGuess != 0) {
    if(contestantGuess <= correctGuess) {
        winningGuess = contestantGuess;
    }
}

但这将使所有数字成为获胜的猜测。

有人可以帮我构建一个正确的 if 语句或只编写伪代码也会有所帮助。

4

3 回答 3

1

只需循环选项并跟踪“最小”距离。

minDistance = 50000000;  // arbitrarily high
for num in numbers {
     if num > correctGuess
          continue;    // skip numbers higher than correctGuess
     newDistance  = correctGuess - num
     if newDistance < minDistance
             minDistance = newDistance
             winngingGuess = num
于 2013-07-01T14:50:19.030 回答
0

创建一个变量来接近获胜者。

const int SIZE = 6;
int inputs[SIZE] = {12,9,7,13,4,0};
const int winningNumber = 15;
int matchIndex = -1;
int matchDifference = INT_MAX;
for(int i = 1; i < SIZE; ++i){
 int difference = std::abs( winningNumber - inputs[i]); //find the difference, how far apart
 if(difference < matchDifference){ //if smaller difference, i.e closer to winning number
   matchIndex = i; //save new closer data info
   matchDifference = difference;
 }       
}

std::cout << "Closest winning number to " << winningNumber << " is : " << inputs[matchIndex]  << endl;
于 2013-07-01T14:52:21.897 回答
0

您将需要变量来跟踪最小差异以进行比较。

int guesses[6] = { 12, 9, 7, 13, 4, 0};
int target = 15, win = -1, minDiff = 1000, diff;

foreach number in guesses //go through each number in the array
{
    if (number == target) //if number matches, you're done
    {
        win = number;
        break;
    }
    else if (number < target) //only proceed checking if number is less than target
    {
        diff = target - number;
        if (diff < minDiff) //if found a closer winner
        {
            minDiff = diff; //update the min difference
            win = number; //set the winner to the current number
        }
    }
}
于 2013-07-01T15:10:09.987 回答