创建计算百分比的C程序给了我一个问题

时间:2013-10-09 19:48:45

标签: c

我正在创建一个民意调查,询问一些问题并显示结果。一个是计算工作和结婚的女学生的百分比。我一直得到百分比结果为0.00,我不确定为什么。以下是我对该项目部分的代码

char pollAnswer[0];
char Gender[0];
int i = 0;
float female = 0;
int enteredAge;
float age = 0;
char work[0];
char married[0];
float workMarried=0;
float percentFemale;
int numChildren;
float childrenAge;
int socialMedia;
int twitter = 0;
int facebook = 0;
int google = 0;
int linkedln = 0;




do {
    printf("1) Gender? (F/M)\n");
    scanf("%s", &Gender[i]);

    if (Gender[i] == 'F') {
        female++;
    }

    printf("2) How old are you?\n");
    scanf("%d", &enteredAge);

    if (enteredAge <= 25) {
        age ++;
    }

    printf("3) Do you work? (Y/N)\n");
    scanf("%s", &work[i]);

    printf("4) Are you married? (Y/N)\n");
    scanf("%s", &married[i]);

    if (work[i] == 'Y' && married[i] == 'Y') {
        workMarried++;
    }


    //Need help with children part.
    //printf("5) how many children do you have?");
    //scanf("%d", &numChildren);

    printf("6) What is the social media you use the most?\n 1. Twitter\n 2. Facebook\n 3. Google+\n 4. Linkedln\n Social Media (1-4): ");
    scanf("%d", &socialMedia);

    if (enteredAge <= 25) {
        if (socialMedia == 1){
            twitter++;
        }
        else if (socialMedia == 2){
            facebook++;
        }
        else if (socialMedia == 3){
            google++;
        }
        else linkedln++;
    }


    printf("Do you want to answer the poll? (Y/N)\n");
    scanf("%s", &pollAnswer[i]);
} while (pollAnswer[i] == 'Y');


percentFemale = (workMarried / female);

printf("What percent of female students work and are married? %f\n", percentFemale);

//Code for average age of the children.

printf("What is the favorite social media of the students with an age less than or equal to 25 years?\n");

if (twitter > facebook && twitter > google && twitter > linkedln) {
    printf("Twitter\n");
}

else if (facebook > twitter && facebook > google && facebook > linkedln) {
    printf("Facebook\n");
}

else if (google > twitter && google > facebook && google > linkedln) {
    printf("Google+\n");
}

else if (linkedln > twitter && linkedln > google && linkedln > facebook) {
    printf("Linkedln\n");
}

return 0;
}

2 个答案:

答案 0 :(得分:2)

您的数组声明是错误的,您正在创建0 size数组,例如:

char pollAnswer[0];

创建足够大的数组以将值存储为char pollAnswer[SIZE];,然后索引可以从0SIZE - 1

第二个scanf语句错误,因为您希望scanf只有一个char:

scanf("%s", &Gender[i]);

将其更正为:

scanf("%c", &Gender[i]);

你得到0.00因为下面的代码永远不会有机会执行,因为你没有使用错误的格式字符串来存储char而是地址:

  if (work[i] == 'Y' && married[i] == 'Y') {
        workMarried++;
    }

workMarried仍为0,答案为0.00。

答案 1 :(得分:1)

收取这些声明

char pollAnswer[0]; 
char Gender[0];
char work[0];
char married[0];

你只需要角色

char pollAnswer;
char Gender;
char work;
char married;

如果您遇到转义scanf()

的问题

在格式说明符之前使用空格。 例如

scanf(" %c", &work);