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

标签 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!

最佳答案

如果您只是计算两个数字之间的差值,为什么不使用 abs(num1 - num2)? 这样您就不必关心顺序。

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

关于c++ - 无法弄清楚如何总是从较大的数字中减去较小的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13117388/

相关文章:

c++11 - std::numeric_limits::quiet_NaN() 与 std::nan() 与 NAN

c++ - cmath 中的 pow() 实现和高效替换

c++ - 如何用语法表示动力学方程

c++ - 编译时检查所有数组值是否已填充

python - 手动实现OpenCV Sobel函数

c++ - 您将如何使用 C++11 初始化函数结果的 const vector ?

c++ - C/C++ 中的嵌套注释

C# WinForms 程序,能够为其制作 C++ 插件

c++-cli - VS2010 C++ 数学支持(未找到 sin 标识符)

c++ - 为什么我的非递归 sqrt 函数是递归的?