C ++是否仍保存“原始值的引用”?

我正在学习C ++,我有以下代码:

long long unsigned number;
cout << "Introduce a non negative number: \n";
cin >> number;
cout << "The number is equal to: " << number << endl;
cout << number*number;

当我引入一个负值时,例如-1,消息显示该数字等于18446744073709551615,这很好,因为我将long定义为一个非负数,所以这个数字有点像错误。

对我来说似乎很奇怪的是,该数字的平方给出正确的值,在输入为-1的情况下为1。

尽管通过键盘输入的数据在数据类型(无符号)方面不正确,但是C ++继续提供原始输入值(-1),就好像它存储在某处一样。

那么,C ++在哪里保存该价值?我如何得到它?

同样,如果我将正方形另存为:

int a = number*number, per example in the case of input -1, a = 1

But when i do cout << a/n; its show 0 instead of 1/1 = 1 (Which I suppose is related to this)

评论
本明远
本明远

This is because of modular arithmetic. When you assign -1 to an unsigned number, it gets stored as a number of the form 2^n - 1 (n depends on the archtecture, but is the largest possible positive number of that type).

All operations on values of this type follow the same modular arithmetic. So when you multiply 2 -1s, you are actually doing:

=> (2^n - 1) x (2^n - 1) mod 2^n
=> 2^(2n) -2^(n+1) + 1 mod 2^n
=> 1 mod 2^n  

Explaining the result of 1.

点赞
评论