Help a beginner: Problem in C

A place to discuss the implementation and style of computer programs.

Moderators: phlip, Moderators General, Prelates

SkinnyPapa
Posts: 3
Joined: Tue Oct 27, 2009 7:56 pm UTC

Help a beginner: Problem in C

Postby SkinnyPapa » Tue Oct 27, 2009 8:08 pm UTC

Hello,
First post on the forum, so go easy on me... I did the warning threads and I hope i'm not violating any forum etiquette by asking for some homework help.

So, the gist:
1st year in university, intro to Comp-Sci. first homework assignment.
Problem statement:
Run a survey on the students in your class, ask them if they prefer:
1) To study in the morning (m) or the evening (e)
2) To study alone (a) or in a group (g)
3) To study with music (m) or in silence (s)

than, print out the percentage of every preference.
the output should look like this:

Code: Select all

How many students will participate in the survey?
3
Student 1:
1)Do you study in the morning (m) or in the evening (e)?
m
2)Do you study alone (a) or with a group (g)?
a
3)Do you study with music (m) or prefer silence (s)?

Student 2:
1)Do you study in the morning (m) or in the evening (e)?
e
2)Do you study alone (a) or with a group (g)?
a
3)Do you study with music (m) or prefer silence (s)?

Student 3:
1)Do you study in the morning (m) or in the evening (e)?
m
2)Do you study alone (a) or with a group (g)?
a
3)Do you study with music (m) or prefer silence (s)?
m
================================================================================================
The results are:
From a group of 3 students:
66.67% of the students study in the morning and 33.33 % in the eveni
100.00% of the students study alone and 0.00% in group.
66.67% of the students study with music and 33.33% in silence.


I've attached my code, which compiles and runs without crashing (woo-hoo! finally) but seems to have some errors:
1) Every OTHER question (as in, one in two) doesn't accept an answer.
2) the percentages at the end are all zero :(

I would REALLY appreciate anyone giving any sort of advice (including persuading me to drop this and go play in traffic...)
Thanks in advance!


CODE:

Code: Select all

#include <stdio.h>

int main()
{
   
    int i, num_students, num_morning, num_e, num_a, num_g, num_music, num_s;
    double perc_morning, perc_e, perc_a, perc_g, perc_music, perc_s;
    char study_time, study_together, study_music;
   
    num_students= num_morning= num_e= num_a= num_g= num_music= num_s= 0;
    printf("How many students will participate in the survey? \n");
    scanf("%d", &num_students);
    for (i=0; i<num_students; i++){
        //Question 1
        printf("1)Do you study in the morning (m) or in the evening (e)? \n");
        scanf("%c", &study_time);
        if (study_time == 'm'){
                       num_morning++;
                       }
        if (study_time == 'e') {
                      num_e++;
                      }
        if (study_time != 'e' && study_time != 'm'){
                       printf("Your answer is not valid and was not counted \n");
                       }
        //Question 2
        printf("2)Do you study alone (a) or with a group (g)? \n");
        scanf("%c", &study_together);
        if (study_together == 'a'){
                       num_a++;
                       }
        if (study_together == 'g') {
                      num_g++;
                      }
        if (study_together != 'a' && study_together != 'g'){
                       printf("Your answer is not valid and was not counted \n");
                       }
        //Question 3
        printf("3)Do you study with music (m) or prefer silence (s)? \n");
        scanf("%c", &study_music);
        if (study_music == 'm'){
                       num_music++;
                       }
        if (study_music == 's') {
                      num_s++;
                      }
        if (study_music != 'm' && study_music != 's'){
                       printf("Your answer is not valid and was not counted \n");
                       }
        }
        perc_morning = num_morning / num_students * 100;
        perc_e = num_e / num_students * 100;
        perc_a = num_a / num_students * 100;
        perc_g = num_g / num_students * 100;
        perc_music = num_music / num_students * 100;
        perc_s = num_s / num_students * 100;
        printf("=======================================================\n");
        printf("The results are: \n From a group of %d students: \n", num_students);
        printf("%lf of the students study in the morning and %lf%% in the evening \n", perc_morning, perc_e);
        printf("%lf of the students study alone and %lf%% in a group \n", perc_a, perc_g);
        printf("%lf of the students study with music and %lf%% in silence", perc_music, perc_s);
    return 0;
}
Last edited by SkinnyPapa on Tue Oct 27, 2009 8:29 pm UTC, edited 1 time in total.

0xBADFEED
Posts: 687
Joined: Mon May 05, 2008 2:14 am UTC

Re: Help a beginner: Problem in C

Postby 0xBADFEED » Tue Oct 27, 2009 8:19 pm UTC

SkinnyPapa wrote:I've attached my code

I don't see it. Just copy it into some 'code' tags.

User avatar
bocochoco
Posts: 317
Joined: Thu Aug 06, 2009 8:22 pm UTC

Re: Help a beginner: Problem in C

Postby bocochoco » Tue Oct 27, 2009 8:21 pm UTC

SkinnyPapa wrote:(including persuading me to drop this and go play in traffic...)


This.

I don't see any code there, just output in code tags.
Image

SkinnyPapa
Posts: 3
Joined: Tue Oct 27, 2009 7:56 pm UTC

Re: Help a beginner: Problem in C

Postby SkinnyPapa » Tue Oct 27, 2009 8:30 pm UTC

Whoops :oops:
Edited.

fazzone
Posts: 186
Joined: Wed Dec 10, 2008 9:38 pm UTC
Location: A boat

Re: Help a beginner: Problem in C

Postby fazzone » Tue Oct 27, 2009 8:55 pm UTC

SkinnyPapa wrote:1) Every OTHER question (as in, one in two) doesn't accept an answer.
2) the percentages at the end are all zero :(

1) Because scanf is weird (The intricacies of scanf are just about the easiest thing to get tripped up with in C, IMO), you should change all your

Code: Select all

scanf("%c" ...
to

Code: Select all

scanf("\n%c" ...
.
2) Because both num_students and the counters are integers, the percentage is calculated with integer arithmetic(truncated), so anything less than 1 is zero. You can fix this by casting at least one (or both) of the operands to double, like so:

Code: Select all

some_percentage = (float)some_integer/(float)some_other_integer
.
Don't feel bad about either of these, they're really tricky, especially for a new C programmer.
*/

eric.lifka
Posts: 10
Joined: Thu May 21, 2009 1:58 am UTC

Re: Help a beginner: Problem in C

Postby eric.lifka » Tue Oct 27, 2009 8:56 pm UTC

Just from a quick glance through, when you calculate the the percentages you use an expression like this:
groupA / total * 100;
Mathematically of course that's right, but you'll always get zero. groupA is an integer that is almost always less than total, which is also an integer (groupA would be equal to total only if all students selected the same option). When doing integer division, all results are truncated, so 3 / 2 becomes 1, not 1.5, which means that if the numerator is less than the denominator you'll always get zero (because order of evaluation is left to right, so the * 100 isn't done until it's too late...). The easy solution is to change your code to this: groupA * 100 / total. By multiplying groupA by 100 first you ensure that it is larger than total, and get an integer percentage, like 66%. if you want the full decimal percentage as well then just change 100 to 100.0. Making the number a floating point number (ie it has a '.' in it), you'll get the compiler to automatically 'upgrade' your other values to floating point, giving you decimal precision results. Then of course you would have to change the variables you store the results to to either type double or type float. EDIT: I just realized that your results variables are already type double, so that last comment doesn't apply.

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

Re: Help a beginner: Problem in C

Postby Berengal » Tue Oct 27, 2009 9:11 pm UTC

As for the input, 'scanf("%c", &var)' doesn't match any whitespace unless you turn it on explicitly. This means the input sequence "1*RETURN*m*RETURN*a*RETURN*s*RETURN*" would be read by scanf as {'1', '\n', m, '\n', a, '\n', s, '\n'}, which is why every other answer is "skipped" (doesn't wait for input, because it already has some left; the next newline).

You can match whitespace manually by putting some whitespace in the format string, like 'scanf(" %c", &var)'.

Note that if you put the whitespace after the %c identifier it tries to match more whitespace until the next non-whitespace character, which won't be consumed, but will be taken as the answer to the next question, even though it was input before the question was output, so put the space in front.

Some functions are magic. scanf is one of them. Read up on their useage before using them.
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

SkinnyPapa
Posts: 3
Joined: Tue Oct 27, 2009 7:56 pm UTC

Re: Help a beginner: Problem in C

Postby SkinnyPapa » Tue Oct 27, 2009 9:54 pm UTC

My god! I didn't know the internet could be productive to school. especially xkcd, which is responsible for many hours of should-be work.

Thank you guys so much, it now works and I can go to bed, just a little more confident in the kindness of strangers :)

G'night.

|Erasmus|
Branson
Posts: 2643
Joined: Tue Oct 30, 2007 7:53 am UTC
Location: Sydney, Australia
Contact:

Re: Help a beginner: Problem in C

Postby |Erasmus| » Thu Oct 29, 2009 2:18 am UTC

Berengal wrote:As for the input, 'scanf("%c", &var)' doesn't match any whitespace unless you turn it on explicitly. This means the input sequence "1*RETURN*m*RETURN*a*RETURN*s*RETURN*" would be read by scanf as {'1', '\n', m, '\n', a, '\n', s, '\n'}, which is why every other answer is "skipped" (doesn't wait for input, because it already has some left; the next newline).

couldn't you just flush stdin after you read the character, to remove any whitespace hanging around in there?
my first thought upon reading the code, at least.

User avatar
jaap
Posts: 2094
Joined: Fri Jul 06, 2007 7:06 am UTC
Contact:

Re: Help a beginner: Problem in C

Postby jaap » Thu Oct 29, 2009 8:01 am UTC

|Erasmus| wrote:couldn't you just flush stdin after you read the character, to remove any whitespace hanging around in there?
my first thought upon reading the code, at least.

Flushing is only defined for output streams:
C standard wrote:If stream points to an output stream or an update stream in which the most recent
operation was not input, the fflush function causes any unwritten data for that stream
to be delivered to the host environment to be written to the file; otherwise, the behavior is
undefined.

Flushing an input stream may do what you want, but it is not guaranteed.
The only guaranteed way to 'flush' an input stream is to read from it until it is empty.

|Erasmus|
Branson
Posts: 2643
Joined: Tue Oct 30, 2007 7:53 am UTC
Location: Sydney, Australia
Contact:

Re: Help a beginner: Problem in C

Postby |Erasmus| » Thu Oct 29, 2009 1:02 pm UTC

been a few years since i implemented something that read stuff from the console using scanf...

I get the feeling I might have implemented by own 'flush' function for stdin that just read all available data so I could use it like that.


Return to “Coding”

Who is online

Users browsing this forum: No registered users and 11 guests