英文:
C C++ Unexpected Output
问题
#include <stdio.h>
int main() {
char Roman[] = "IVXLCDM";
int Num[] = {1, 5, 10, 50, 100, 500, 1000};
int n = 0;
do
{
printf("%i\n", Num[n]); // Corrected this line to print the values from the Num array.
n++;
} while (n < 7);
return 0;
}
输出应该是:
1
5
10
50
100
500
1000
问题在于原始代码中,您尝试将Num数组的值赋给Roman数组,这导致了错误的输出。已经将代码修改为正确地从Num数组中打印值。
英文:
#include <stdio.h>
int main() {
char Roman[] = "IVXLCDM";
int Num[] = {1,5,10,50,100,500,1000};
int n = 0;
do
{
Roman[n]=Num[n] ;
printf("%i\n", Roman[n]);
n++;
} while (n<7);
return 0;
}
For above code I expect the output:
1
5
10
50
100
500
1000
But it's producing:
1
5
10
50
100
-12
-24
Can someone explain what the problem is?
答案1
得分: 5
char
在你的情况下是一个8位有符号数字,只能保存-128到127的值。当你将500和1000赋给一个char
时,它会丢弃这些值的低八位以外的部分。500 - 512 == -12,1000 - 1024 == -24。
(C标准允许char
是一个8位无符号数字,这种情况下你会看到244和232。)
英文:
char
in your case is an 8-bit signed number, which can only hold the values -128 to 127. When you assign 500 and 1000 to a char
, it throws out all but the low eight bits of those values. 500 - 512 == -12, 1000 - 1024 == -24.
(The C standard permits char
to be an 8-bit unsigned number, in which case you would have seen 244 and 232.)
答案2
得分: 2
在C++中,我会使用一个map:
std::map<std::string, int> romanNumerals{{"I", 1}, {"V", 5}, {"X", 10},
{"L", 50}, {"C", 100},
{"D", 500}, {"M", 1000}};
for (const auto& [key, value] : romanNumerals) {
cout << key << ":" << value << "\n";
}
英文:
In C++, I would use a map:
std::map<std::char, int> romanNumerals{{"I", 1}, {"V", 5}, {"X", 10},
{"L", 50}, {"C", 100},
{"D", 500}, {"M", 1000}};
for (const auto& [key, value] : romanNumerals) {
cout << key << ":" << value << "\n";
}
答案3
得分: 0
char类型只能保存范围为-128到+127的数字;总共256个。即使将类型设置为unsigned char,也无法存储最后两个数字。
尝试:
int *Roman = (int*)calloc(7, sizeof(int));
英文:
The char type can only hold numbers in the range -128 to +127; 256 in total. Even if you set the type to unsigned char, it still will not be possible to store those last two numbers.
Try;
int *Roman = (int*)calloc(7, sizeof(int));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论