0

我正在创建一个询问一些问题并显示结果的民意调查。一是计算工作和已婚的女学生的百分比。我一直得到 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;
}
4

2 回答 2

2

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

char pollAnswer[0];

创建足够大的数组来存储值,因为char pollAnswer[SIZE];索引可以是 from0SIZE - 1

第二个scanf语句是错误的,因为您只想scanf单个字符:

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

更正为:

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

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

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

workMarried剩下0,答案是 0.00。

于 2013-10-09T19:51:24.293 回答
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);
于 2013-10-09T19:54:48.467 回答