我打算用 C++ 来做这个,但我不得不用几种语言来做,这是一个相当普遍和简单的问题,这是最后一次。我已经写够了,我确信一定有更好的方法,所以在我用另一种语言写出同样冗长的方法之前,我先在这里发帖;
考虑下面的 (lilies!) 代码;
// I want the difference between these two values as a positive integer
int x = 7
int y = 3
int diff;
// This means you have to find the largest number first
// before making the subtract, to keep the answer positive
if (x>y) {
diff = (x-y);
} else if (y>x) {
diff = (y-x);
} else if (x==y) {
diff = 0;
}
这听起来可能很琐碎,但对我来说似乎很多,只是为了得到两个数字之间的差异。这实际上是一种完全合理的做事方式,而我是不必要的迂腐,还是我的蜘蛛侠感觉有充分的理由?
最佳答案
只要得到差的绝对值:
#include <cstdlib>
int diff = std::abs(x-y);
关于c++ - 计算两个数字之间差异的最短方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10589559/