0

The code doesn't give me the right decimal answers after calculating, and it also doesn't prompt the user to re enter the right value when it's less than 9,as I expected. I'm new in programming, can I please get help on what to do. Here is the code

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

int main(void)
{
    float i = get_float("first population: ");
    float j = get_float("second population: ")

    if (i < 9)
    {
        printf ("%f",'i');
    }
    if (j < 9)
    {
        printf ("%f",'j');
    }
    float n = (i/3);
    float m = (i/4);

    float d = (n - m);
    float a = (i + d);

    float x = (j - i);
    float y = (j/a);

    printf ("%f", y\n);
}
0

1 Answer 1

0

The problem is that you have no logic to retry if the input is not what you want.

if you want the user to be reprompted for another input if i < 9 for example you would have to do the following:

float i = 0;
while ( i < 9 ) {
    i = get_float("first population: ");
}

That will insure that they have entered a value that is at least 9. However I dont think you want a float there. Assuming you are doing the first problem about population you can't have a half a llama. So 10.5 wouldnt be valid.. I think what you want is an integer.

Note I'm also going to rename variables to give them some meaning

int start = 0;  # note change to int
while ( start < 9 ) 
{   // using a while loop says while start is less than 9 do the actions inside here
    // note I have used get_int and changed prompt to match the instructions
    start = get_int("Start size: ");
}

The second value should also be an integer and is end value

int end = 0;
while ( end < start )
{
    end = get_int("End size: ");
}

now we have valid start and end population targets.

then we do the next phase

int current = start;
//???? need something here to make this cycle repeat until you reach the goal
int born = current / 3;
int dead = current / 4;
int current = current + born - dead;
// ???? and need something here to count the number of years it takes

You cant just do this once and divide by difference by what amounted to (start + born - dead) because a different amount will be born and die each year, you have to iteratively do this out in a loop of some kind. I leave it up to you to figure that part out but I have left some hints in place.

You must log in to answer this question.

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