0

我有整个程序,除了它总是从较大的数字中减去较小的数字的部分。我一直试图找到它,但我找不到任何可以帮助我的东西。这是我唯一需要帮助的部分。

这是代码。

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

//function prototype
int getRandomNumber(int lower, int upper);

int main()
{
//declare variables
int smallest = 0;
int largest = 0;
int num1 = 0;
int num2 = 0;
int correctAnswer = 0;
int userAnswer = 0;

//initialize rand function
srand(static_cast<int>(time(0)));

cout << "Smallest Integer: ";
cin >> smallest;
cout << "Largest Integer: ";
cin >> largest;
cout << endl;

for (int x = 1; x < 6; x += 1)
{
//generate two random integers
//from smallest through largest, then
//calculate the sum
num1 = getRandomNumber(smallest, largest);
num2 = getRandomNumber(smallest, largest);
correctAnswer = num1 - num2;

//display addition problem and get user's answer
cout << "what is the difference of " << num1 <<" - " << num2 << " ? ";
cin >> userAnswer;

//determine wether user's answer is correct
if (userAnswer == correctAnswer)
cout << "Correct";
else
cout << " Sorry, the correct answer is " << correctAnswer << ".";
//end if
cout << endl << endl;
} //end for

return 0;
} //end of main function

//*****function definitions*****
int getRandomNumber(int lower, int upper)
{
int randInteger = 0;
//generate random integer from lower through upper
randInteger = lower + rand() % (upper - lower + 1);
return randInteger;
} //end of getRandomNumber function

need help!
4

3 回答 3

4

如果您只关注两个数字之间的差异,为什么不使用 abs(num1 - num2)?那么你就不必关心订单了。

http://www.cplusplus.com/reference/clibrary/cmath/abs/

于 2012-10-29T07:23:05.597 回答
2

这似乎很简单。

if (num1 < num2)
   correctAnswer = num2 - num1;
else
   correctAnswer = num1 - num2;
于 2012-10-29T07:25:49.657 回答
1

只需将逻辑放入函数中,然后进行简单的布尔检查来决定返回哪个结果。

int SubstractSmallerNumber(int num1, int num2){
    if(num1 < num2) return num2 - num1;
    else return num1 - num2;
}

这是一种蛮力方法,您可以找到更聪明的方法来解决问题。想想绝对价值。如果你取减法的绝对值,你会得到同样的净效果。

于 2012-10-29T07:26:19.573 回答