我试图制作一个程序(在VS 2019中),该程序可以打印出某些字符的每个值,但效果似乎不太理想。执行后,无论我输入哪个,它都会打印出数字“ 0”。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct value //Value for each characters
{
char tier;
int weight;
float airspeed;
float fallspeed;
float fastfall;
float dash;
}V;
V mario; //I set 'Mario' as a variable.
V mario; tier = 'A';
V mario; weight = 98;
V mario; airspeed = 1.208f;
V mario; fallspeed = 1.5f;
V mairo; fastfall = 2.4f;
V mario; dash = 1.76f;
int main(void)
{
printf("%d", mario.weight); //mario.weight is '98'.
return 0;
}
我以为“ mario.weight”将被打印为“ 98”,但是当我执行它时,其被打印为“ 0”。
您可以做类似的事情
V mario={'A',98,1.208f,1.5f,2.4f,1.76f};
或
V mario={.tier='A',.weight=98,.airspeed=1.208f,.fallspeed=1.5f,.fastfall=2.4f,.dash=1.76f};
1)在您的代码中>
V mario; //I set 'Mario' as a variable. V mario; tier = 'A'; V mario; weight = 98; V mario; airspeed = 1.208f; V mario; fallspeed = 1.5f; V mario; fastfall = 2.4f; V mario; dash = 1.76f;
全部
V mario;
转到暂定的定义,默认为0。
2)此处
tier,weight,airspeed,fallspeed,fastfall,dash.
全部为默认值,您可以通过将mario.weight更改为printf中的weight来进行检查,它将打印98。
3)全局变量在定义时可以初始化,但是您不能这样做,因为它不是初始化
V mario; //I set 'Mario' as a variable. mario.tier = 'A'; mario.weight = 98; mario.airspeed = 1.208f; mario.fallspeed = 1.5f; mario.fastfall = 2.4f; mario.dash = 1.76f;
但是您可以主要执行此操作,如果您想知道为什么这不可能的话,请参阅此
Why can't I assign values to global variables outside a function in C?
有关暂定定义的信息,请参见此https://www.ibm.com/support/knowledgecenter/en/ssw_ibm_i_71/rzarg/tentative_defn.htm