c++ 计算两个数字之间的差距的最短方法?

栏目: C++ · 发布时间: 7年前

内容简介:代码日志版权声明:翻译自:http://stackoverflow.com/questions/10589559/shortest-way-to-calculate-difference-between-two-numbers

我要在C中这样做,但是我不得不用多种语言来做,这是一个相当普遍和简单的问题,这是最后一次.我已经有足够的编码,我确定必须有一个更好的方法,所以我发布在这里之前,我用另一种语言写出相同的长风方法;

考虑(百合!)以下代码;

// 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);

代码日志版权声明:

翻译自:http://stackoverflow.com/questions/10589559/shortest-way-to-calculate-difference-between-two-numbers


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

JavaScript Patterns

JavaScript Patterns

Stoyan Stefanov / O'Reilly Media, Inc. / 2010-09-21 / USD 29.99

What's the best approach for developing an application with JavaScript? This book helps you answer that question with numerous JavaScript coding patterns and best practices. If you're an experienced d......一起来看看 《JavaScript Patterns》 这本书的介绍吧!

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具