结构变量数据在结构定义中声明时出错

时间:2015-11-01 07:32:14

标签: c++

在这种情况下,程序的工作方式与预期一致。

#include <iostream>
struct candyBar
{
    char brandName[20];
    double weight;
    int calories;
};

int main()
{
    using namespace std;
    candyBar snack = { "Mocha Much", 2.3, 350 };
    cout << snack.brandName << "\t" << snack.weight << "\t" << snack.calories << endl;
    return 0;
}

但在此迭代中,在定义struct candyBar 之后声明变量 snack 时,程序会显示以下警告:

  • (第13行):警告C4244:'初始化':从'double'转换为'char',可能会丢失数据
  • (第13行):警告C4305:'初始化':从'int'截断到'char'
  • (第13行):警告C4309:'初始化':截断常数值

程序会为 brandName weight 成员输出正确的值,但会将卡路里的值更改为350.为什么这会发生吗?

#include <iostream>
struct candyBar
{
    char brandName[20];
    double weight;
    int calories;
} snack;

int main()
{
    using namespace std;
    snack = { "Mocha Much", 2.3, 350 };
    cout << snack.brandName << "\t" << snack.weight << "\t" << snack.calories << endl;
    return 0;
}

0 个答案:

没有答案
相关问题