绝对值/减法

时间:2016-02-14 07:55:43

标签: 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);
    }
}

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

4 个答案:

答案 0 :(得分:1)

对于初学者,类型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

答案 1 :(得分:0)

你的病情写错了。应该是

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

但是,您的条件if(x && y <= 1000000000000000)会以简单的英语评估if x is true AND y is less than or equal to 1000000000000000,这绝对不是您想要的。您已完成的方式,当y小于1000000000000000x为除零以外的任何值,正数或负数时,条件将评估为真。这背后的原因是在C中任何非零值的计算结果为真。

注意:在xy分配的任何值不在int范围内(-2 ^ 31到2)时,您的代码都会失败^ 31-1(将int视为32位,这是最常见的)。您必须在long longxy使用z数据类型。

long long x, y, z;

long long的范围为-2 ^ 63到2 ^ 63-1,其大小足以容纳指定范围内的任何数字,即01000000000000000

答案 2 :(得分:0)

你的if条件是错误的,正如其他人已提到的那样。对于除零之外的每个值,变量x的结果为true。所以你必须写(x <= MAX&amp;&amp; y&lt; = MAX)。

此外,您可以使用函数numeric_limits(限制库)阻止使用固定最大值购买:

#include <iostream>
#include <limits>
#include <cmath> 

int main() {
int x;
int y;
int z;

std::cin >> x >> y;

if (x <= std::numeric_limits<long>::max() && y <= std::numeric_limits<long>::max()) {
z=x-y;
std::cout << std::abs (z);
}
}

答案 3 :(得分:0)

我使用node.js来解决它;像这样:

let line;
const results = [];
var readline = require('readline');
var fs = require('fs');
var myInterface = readline.createInterface({
input: fs.createReadStream('sample.in')
});
var lineno = 0;
myInterface.on('line', function (line) {

const numbers = line.split(' ');
const firstNo = numbers[0];
const secondNo = numbers[1];
console.log(Math.abs(firstNo - secondNo));
lineno++; 
});