好吧,我想猜测最接近中奖号码的一系列数字(忽略平局的可能性),让我们说中奖号码是15。
我也想确保它不会超过中奖号码。最后一个条件是,如果所有的猜测都太大,就没有赢家。
假设数字如下:
12
9
7
13
4
0
我希望程序选择13作为中奖号码。
这是我写的代码的剪辑:
corrrectGuess = 15
while(contestantGuess != 0) {
if(contestantGuess <= correctGuess) {
winningGuess = contestantGuess;
}
}
但这将使所有数字成为胜利的猜测。
有人可以帮我构建一个正确的if语句,或者只编写伪代码也会有所帮助。
答案 0 :(得分: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
答案 1 :(得分: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;
答案 2 :(得分: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
}
}
}