已初始化的数据成员值不正确地存储在结构中。

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

Initialized data member values incorrectly stored in struct

问题

问题场景

  1. #include <iostream>
  2. using namespace std;
  3. struct sec
  4. {
  5. int a;
  6. char b;
  7. };
  8. int main()
  9. {
  10. struct sec s ={25,50};
  11. cout << "struct sec的大小: " << sizeof(s) << endl;
  12. cout << "a: " << s.a << " b: " << s.b << endl;
  13. return 0;
  14. }
  1. 输出:
  2. struct sec的大小: 8
  3. a: 25 b: 2

"a = 25"和"b = 50"结构数据成员的初始值。然而,保存的值不正确。

适用于整数类型。

  1. #include <iostream>
  2. using namespace std;
  3. struct sec
  4. {
  5. int a;
  6. char b;
  7. };
  8. int main()
  9. {
  10. struct sec s ={25,50};
  11. cout << "struct sec的大小: " << sizeof(s) << endl;
  12. cout << "a: " << s.a << " b: " << s.b << endl;
  13. return 0;
  14. }
  1. 输出:
  2. struct sec的大小: 8
  3. a: 25 b: 50
英文:

Problematic scenario

  1. #include <iostream>
  2. using namespace std;
  3. struct sec
  4. {
  5. int a;
  6. char b;
  7. };
  8. int main()
  9. {
  10. struct sec s ={25,50};
  11. cout << "size of struct sec: " << sizeof(s) << endl;
  12. cout << "a: " << s.a << " b: " << s.b << endl;
  13. return 0;
  14. }
  1. output:
  2. size of struct sec: 8
  3. a: 25 b: 2

Initial values for the "a = 25" and "b = 50" struct data members. however the incorrect value was saved.

Works for integer types.

  1. #include <iostream>
  2. using namespace std;
  3. struct sec
  4. {
  5. int a;
  6. char b;
  7. };
  8. int main()
  9. {
  10. struct sec s ={25,50};
  11. cout << "size of struct sec: " << sizeof(s) << endl;
  12. cout << "a: " << s.a << " b: " << s.b << endl;
  13. return 0;
  14. }
  1. output:
  2. size of struct sec: 8
  3. a: 25 b: 50

答案1

得分: 3

你正在打印一个值为50的字符,这是ASCII代码表示的数字'2'。尝试:

  1. cout << "a: " << s.a << " b: " << (int)s.b << endl;
英文:

You are printing a char of value 50, which is the ascii code for '2'. Try:

  1. cout &lt;&lt; &quot;a: &quot; &lt;&lt; s.a &lt;&lt; &quot; b: &quot; &lt;&lt; (int)s.b &lt;&lt; endl;

huangapple
  • 本文由 发表于 2023年7月11日 13:01:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76658832.html
匿名

发表评论

匿名网友

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

确定