c++ - 绝对值/减法

标签 c++ absolute subtraction

我正在尝试解决一个问题:

编写一个程序计算非负整数之间的差值。

输入:

输入的每一行都由一对整数组成。每个整数都在 0 到 10 之间提高到 15(含)。输入在文件末尾终止。

输出:

对于输入中的每一对整数,输出一行,包含它们差的绝对值。

这是我的解决方案:

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

int main(){
    int x;
    int y;
    int z;
    
    cin >> x >> y;
    
    if(x && y <= 1000000000000000){
        z=x-y;
        cout << std::abs (z);
    }
}

但问题是我的答案错了,请帮我更正我的答案并解释为什么错了。

最佳答案

对于初学者来说,int 类型对象的有效值范围通常小于 1000000000000000。 您应该使用足够宽的整数类型来存储这么大的值。合适的类型是 unsigned long long int,因为根据赋值,输入的值是非负数。

否则,您还需要检查这些值是否不是大于或等于零的负数。

还有if语句中的条件

if(x && y <= 1000000000000000){

错了。相当于

if(x && ( y <= 1000000000000000 )){

反过来等同于

if( ( x != 0 ) && ( y <= 1000000000000000 )){

不一样

if ( ( x <= 1000000000000000 ) && ( y <= 1000000000000000 ) ){

程序可以如下所示

#include <iostream>

int main()
{
    const unsigned long long int UPPER_VALUE = 1000000000000000;
    unsigned long long int x, y;

    while ( std::cin >> x >> y )
    {
        if ( x <= UPPER_VALUE && y <= UPPER_VALUE )
        {
            std::cout << "The difference between the numbers is "
                      << ( x < y ? y - x : x - y )
                      << std::endl;
        }
        else
        {
            std::cout << "The numbers shall be less than or equal to " 
                      << UPPER_VALUE 
                      << std::endl;
        }
    }        
}

如果例如输入这些值

1000000000000000 1000000000000000 
1000000000000001 1000000000000000 
1 2

然后程序输出看起来像

The difference between the numbers is 0
The numbers shall be less than or equal to 1000000000000000
The difference between the numbers is 1

关于c++ - 绝对值/减法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35389591/

相关文章:

python - 从给定多个索引的 pandas 数据框中减去系列值

c++ - C++函数指针的困惑

c++ - 为什么缩小转换不能防止错误类型的 map.insert() 失败?

css - 随不同屏幕分辨率移动的页面元素

html - 即 : "overflow: scroll" on parent and "margin: 0 auto" on child do not work properly

c++ - 减法给了我积极的结果 C++

c++ - 从模板类调用函数时形成无限循环,请任何人解释

c++ - 按返回类型进行方法模板特化

html - 如何获得全高菜单div

C - 从另一个字符串中减去一个字符串