C++:类似 mod 操作打印不同的值

C++: Similar mod operations printing different values

我正在尝试执行一些自定义操作,但我注意到以下错误。 在计算 t 的值时,我得到了所需的输出,但是对于 s,我无缘无故地得到了负值。

#include <bits/stdc++.h>

using namespace std;

int main()
{
    char s = 'r';
    char temp1 = s;

    char t = 'a';
    char temp2 = t;

    s = (int(temp1) % int(96)) + (int(s) % int(96)) + 96;
    cout << int(s) << " ";

    t = (int(temp2) % int(96)) + (int(t) % int(96)) + 96;
    cout << int(t) << endl;
}

I have to use this logic elsewhere in a bigger program, I am getting the same error in both the cases

Output -124 98

I don't understand why -124 is begin printed

您遇到了 8 位整数类型 (char) 的溢出问题。

这个表达式是

s = (int(temp1) % int(96)) + (int(s) % int(96)) + 96;

从代数上讲,您的代码可以简化为:

s = 114 % 96 + 114 % 96 + 96;

s = 18 + 18 + 96;

s = (signed char)132;  // overflow!  132 won't fit in range [-128..127]

s = -124;

将 s 和 t 的声明更改为 int 类型。还提供了一些改进代码风格的有用方法:

int main()
{
    int s = 'r';
    int temp1 = s;

    int t = 'a';
    int temp2 = t;

    s = temp1 % 96 + s % 96 + 96;
    cout << s << " ";

    t = temp2 % 96 + t % 96 + 96;
    cout << t << endl;
}