C C++ 非预期输出

huangapple go评论66阅读模式
英文:

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 &lt;stdio.h&gt;

int main() {
    char Roman[] = &quot;IVXLCDM&quot;;
    int Num[] = {1,5,10,50,100,500,1000};
    int n = 0;

    do
    {
        Roman[n]=Num[n] ;
        printf(&quot;%i\n&quot;, Roman[n]);
        n++;
    } while (n&lt;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

C C++ 非预期输出

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&lt;std::char, int&gt; romanNumerals{{&quot;I&quot;, 1}, {&quot;V&quot;, 5}, {&quot;X&quot;, 10}, 
                                       {&quot;L&quot;, 50}, {&quot;C&quot;, 100}, 
                                       {&quot;D&quot;, 500}, {&quot;M&quot;, 1000}};

for (const auto&amp; [key, value] : romanNumerals) {
    cout &lt;&lt; key &lt;&lt; &quot;:&quot; &lt;&lt; value &lt;&lt; &quot;\n&quot;;
}

答案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));

huangapple
  • 本文由 发表于 2023年6月26日 02:19:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76551836.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定