【问题标题】:Cast: functions fun1 and fun2 should the same value but the output is different. Can you explain why is it so?Cast:函数 fun1 和 fun2 应该具有相同的值,但输出不同。你能解释一下为什么会这样吗?
【发布时间】:2020-09-30 19:48:26
【问题描述】:

似乎函数fun1fun2 应该返回相同的值,但输出不同。你能解释一下为什么会这样吗?

#include <iostream>
using namespace std;
long long fun1(int, int, int );
long long fun2(int, int, int );
int main(){
    int l = 1039, b = 3749, h =8473;
   cout<<"Volume is equal to "<<fun1(l,b,h)<<endl;
   cout<<"Volume is equal to "<<fun2(l,b,h)<<endl;
}

long long fun1(int length, int breadth, int height){
    long long volume = length * breadth * height;
    return volume;
}
long long fun2(int length, int breadth, int height){
    return (long long)length * breadth * height;
}

输出:

Volume is equal to -1355615565
Volume is equal to 33004122803

【问题讨论】:

  • 您应该添加语言。很明显它是 C,但没有任何标签,人们几乎没有机会碰到你的问题。

标签: c long-long


【解决方案1】:

第一种情况:

您正在计算 int 类型中的所有内容,然后转换为 long long。不幸的是,结果太大而无法放入int,所以你有一个溢出。即使你将它转换为更大的类型,也为时已晚,溢出已经发生了。

第二种情况:

在实际进行计算之前,您将转换为 long long。因此,计算将使用从intlong long 的隐式转换来完成,结果确实适合您的容器(现在是long long)……没有溢出,生活很美好!

【讨论】:

    猜你喜欢
    • 2022-11-01
    • 1970-01-01
    • 2021-10-17
    • 2010-10-09
    • 1970-01-01
    • 2016-12-23
    • 2013-01-29
    • 2016-07-29
    • 1970-01-01
    相关资源
    最近更新 更多