0

I tried to write this little piece of code, but I couldn't figure it out entirely. Can someone help me with the missing parts?

#include <stdio.h>
#include <cs50.h>

int main(void)
{
printf("Are you hungry?  \n");
string s = GetString();

printf("What is the temperature?  \n");
int temperature = GetInt();
if (hungry=true && (temperature>=27))

printf("Eat icecream!\n");
}
1

You seem to have made quite a few mistakes in your code. This is of course not unusual for someone who's just starting out, so let me point you in the right direction.

  1. You are reading the first reply into a string variable called s. Later on, you refer to it as hungry. Choose whichever you prefer and rename the other instance to the same.
  2. To assign a variable, you have to use a single equality sign (=), and you did that perfectly right. When you are checking a value, on the other hand, you need to use two of these (==).
  3. At your condition, you check to see if hungry is true, but it's supposed to be a string (not a bool, like true or false), so you should check it against another string, like "yes".

Just a friendly reminder: if the user answers "no" (or in fact, anything, but "yes" to your first question, there is no point in asking for the temperature.

Also, even though the compiler won't kill you for emitting the return statement from your main function, you really shouldn't do that. If you don't want to mess around with the exit codes just yet, simply add return 0 at the very end of your main function to indicate that no error has occured.

Here is a working version of your code to help you get started. Hope I could be of help.

int main()
{
    printf("Are you hungry?\n");
    string hungry = GetString();

    if (hungry == "yes")
    {
        printf("What is the temperature?\n");
        int temperature = GetInt();

        if (temperature >= 27)
        {
            printf("Eat icecream!\n");
        }
    }

    return 0;
}

See full file on ideone: http://ideone.com/Tn9PDG

| improve this answer | |

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .