gpt4 book ai didi

c++ - 数据类型的计算不同

转载 作者:搜寻专家 更新时间:2023-10-31 01:33:49 26 4
gpt4 key购买 nike

我对 C++ 还是很陌生,所以这可能是个愚蠢的问题。在下面的代码中,为什么当我将索引类型更改为带符号的字符时,index > 25 的计算结果为 true。 signed char 不就是一个 1 字节的整数吗?

#include <iostream>
using namespace std;

char lowercase [26] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};

int main() {
short index;

cout << "Enter a number 0 to 25: ";
cin >> index;
if (index > 25 || index < 0) {
cout << "That number is out of range." << endl;
return 0;
}
cout << "The lowercase letter for this number is " << lowercase[index] << "." << endl;
return 0;
}

最佳答案

让我们稍微重述一下这个问题:

char index;
cin >> index;

可能更容易看出问题。当您将输入读入 char 时,您会获得用户输入的第一个字符的字符代码。在典型的系统中,这是 ASCII,数字代码在 48 到 57 之间。

因此,当您在 index 中输入一个带符号的字符时,您将得到一个 >= 48 的值。

关于c++ - 数据类型的计算不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40689281/

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