无法弄清楚如何总是从较大的数字中减去较小的数字

时间:2012-10-29 07:17:15

标签: c++ cmath

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

这是代码。

#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!

3 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:2)

看起来很简单。

if (num1 < num2)
   correctAnswer = num2 - num1;
else
   correctAnswer = num1 - num2;

答案 2 :(得分:1)

只需将逻辑放入函数中,然后执行简单的bool检查以确定要返回的结果。

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

这是一种强力方法,您可以找到解决问题的更智能方法。 想想绝对价值。如果你取减法的绝对值,你将得到相同的净效果。