简体   繁体   English

C ++中数学计算中的内部时间变量

[英]Internal temporal variable in mathematic calculation in C++

The following example is used to illustrate my question: 以下示例用于说明我的问题:

#include <iostream>
#include <string>

int main()
{

  signed char p;
  signed char temp=100;
  signed char t=4;
  p = (temp+temp+temp+temp)/t;
  std::cout << "Hello, " << int(p)<< "!\n";
}

In the above codes, variable p is defined as the average of four singed char variables. 在上面的代码中,变量p被定义为四个singed char变量的平均值。 However, the sum of the signed char variable (temp+temp+temp+temp) will be larger than the range of signed char. 但是,signed char变量(temp + temp + temp + temp)的总和将大于signed char的范围。 So my question is how C++ handle this situation. 所以我的问题是C ++如何处理这种情况。

However, the sum of the signed char variable (temp+temp+temp+temp) will be larger than the range of signed char. 但是,signed char变量(temp + temp + temp + temp)的总和将大于signed char的范围。

That does not matter as char will be promoted to int due to integral promotion . 这无关紧要,因为integral promotion会将char提升为int Details can be found here . 细节可以在这里找到。 So operations will be done over type int and you will get expected result. 因此,操作将在int类型上完成,您将获得预期的结果。

Nothing happens, because of integral promotion 没有任何事情发生,因为整体推广

Prvalues of small integral types (such as char) may be converted to prvalues of larger integral types (such as int). 小整数类型(例如char)的Prvalues可以转换为更大整数类型(例如int)的prvalues。 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. 特别是,算术运算符不接受小于int的类型作为参数,并且在左值到右值转换后自动应用整数促销(如果适用)。 This conversion always preserves the value. 此转换始终保留该值。

(temp+temp+temp+temp) will return an integer. (temp+temp+temp+temp)将返回一个整数。

(temp+temp+temp+temp)/t will be inside of the char range. (temp+temp+temp+temp)/t将在char范围内。

so p == temp 所以p == temp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM