gpt4 book ai didi

c++ - C++ 中的 unsigned int 与 unsigned short 的区别

转载 作者:行者123 更新时间:2023-11-30 02:31:19 25 4
gpt4 key购买 nike

我有以下内容:

#include <iostream>                                          

using namespace std;

float f1(unsigned int x, unsigned int y)
{
float val;
val = float(y-x)/(y+x);
return val;
}

float f2(unsigned short x, unsigned short y)
{
float val;
val = float(y-x)/(y+x);
return val;
}

int main()
{
cout << f1(9612, 9038) << "\n" << f2(9612, 9038) << endl;
return 0;
}

在输出中,我从 f1f2 得到两个不同的值,尽管我希望输出相同,因为函数相似。您能解释一下差异的来源吗?

最佳答案

虽然由于这两个函数都使用无符号值,有人可能会认为减法会导致两个值都为正数,但由于整数提升发生在对数字类型的运算符算术求值之前,所以有人会错了。

cppreference describes arithmetic operator conversions:

If the operand passed to an arithmetic operator is integral or unscoped enumeration type, then before any other action (but after lvalue-to-rvalue conversion, if applicable), the operand undergoes integral promotion. If an operand has array or function type, array-to-pointer and function-to-pointer conversions are applied. ...

积分促销是发生这种转化的地方。关于那个主题,cppreference states the following:

Prvalues of small integral types (such as char) may be converted to prvalues of larger integral types (such as int). In particular, arithmetic operators do not accept types smaller than int as arguments, and integral promotions are automatically applied after lvalue-to-rvalue conversion, if applicable. This conversion always preserves the value.

因此,如果在数学运算中使用小于整数的类型,则会将其转换为整数。这是第二种情况下负值的原因——操作数在减法之前转换为 int,结果产生负值。将该特定表达式视为 ((int)y - (int)x) 可能更容易,这使得它显然可以为负数。

关于c++ - C++ 中的 unsigned int 与 unsigned short 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37946090/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com