简体   繁体   中英

Assigning variable in IF statement C

The code below is to output the time taken for a snail to complete a race. I understand an if statement is to be used however I am struggling to find a way to assign my final code- TimeMinutes1 + TimeMinutes2 + TimeMinutes3 + TimeMinutes4, TimeSeconds1 + TimeSeconds2 + TimeSeconds3 + TimeSeconds4 a variable which can be used in conjunction with an IF statement?

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char SquirrelName [20]; 
    int TimeMinutes1;
    int TimeMinutes2;
    int TimeMinutes3;
    int TimeMinutes4;
    int TimeSeconds1;
    int TimeSeconds2;
    int TimeSeconds3;
    int TimeSeconds4;
    int TotalSeconds1;
    int TotalSeconds2;
    int TotalSeconds3;
    int TotalSeconds4;

    printf("What is the name of the squirrel? \n");
    scanf("%s", SquirrelName);

    printf("How long did it take to complete the first lap in Seconds? \n");
    scanf("%d", &TotalSeconds1);

    TimeMinutes1 = TotalSeconds1 / 60;
    TimeSeconds1 = TotalSeconds1 % 60;

    printf("Lap 1 finished in %d minutes and %d seconds\n", TimeMinutes1, TimeSeconds1);

    printf("How long did it take to complete the second lap in Seconds? \n");
    scanf("%d", &TotalSeconds2);

    TimeMinutes2 = TotalSeconds2 / 60;
    TimeSeconds2 = TotalSeconds2 % 60;

    printf("Lap 2 finished in %d minutes and %d seconds\n", TimeMinutes2, TimeSeconds2);

    printf("How long did it take to complete the third lap in Seconds? \n");
    scanf("%d", &TotalSeconds3);

    TimeMinutes3 = TotalSeconds3/ 60;
    TimeSeconds3 = TotalSeconds3 % 60;

    printf("Lap 3 finished in %d minutes and %d seconds\n", TimeMinutes3, TimeSeconds3);

    printf("How long did it take to complete the fourth lap in Seconds? \n");
    scanf("%d", &TotalSeconds4);

    TimeMinutes4 = TotalSeconds4 / 60;
    TimeSeconds4 = TotalSeconds4 % 60;

    printf("Lap 4 finished in %d minutes and %d seconds\n", TimeMinutes4, TimeSeconds4);

    printf("The total time it took for the course to complete was %d minutes and %d seconds\n", TimeMinutes1 + TimeMinutes2 + TimeMinutes3 + TimeMinutes4, TimeSeconds1 + TimeSeconds2 + TimeSeconds3 + TimeSeconds4);

    return 0;
}

Whenever there are multiple/many variables ending in a digit, such as foo1 , foo2 , foo3 , etc. this indicates that we should be using an array [and a loop instead of replicating the code].

If we have multiple parallel arrays that are indexed by the same index variable, such as:

#define LAPCOUNT    4
int time_tot[LAPCOUNT];
int time_min[LAPCOUNT];
int time_sec[LAPCOUNT];

This indicates we should create a struct and have an array of these structs.

Here is a version of your code that uses these ideas:

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int time_tot;
    int time_min;
    int time_sec;
} lap_t;

#define LAPCOUNT    4

int
main(void)
{
    char SquirrelName[20];
    int lapidx;
    lap_t *lap;
    lap_t laplist[LAPCOUNT];
    lap_t laptot;

    printf("What is the name of the squirrel? \n");
    scanf("%s", SquirrelName);

    for (lapidx = 0;  lapidx < LAPCOUNT;  ++lapidx) {
        lap = &laplist[lapidx];

        printf("How long did it take to complete lap %d in Seconds? \n",
            lapidx + 1);

        scanf("%d", &lap->time_tot);

        lap->time_min = lap->time_tot / 60;
        lap->time_sec = lap->time_tot % 60;

        printf("Lap %d finished in %d minutes and %d seconds\n",
             lapidx + 1,lap->time_min, lap->time_sec);
    }

    laptot.time_min = 0;
    laptot.time_sec = 0;
    laptot.time_tot = 0;

    for (lapidx = 0;  lapidx < LAPCOUNT;  ++lapidx) {
        lap = &laplist[lapidx];
        laptot.time_min += lap->time_min;
        laptot.time_sec += lap->time_sec;
        laptot.time_tot += lap->time_tot;
    }

#if 0
    printf("The total time it took for the course to complete was %d minutes and %d seconds\n",
        laptot.time_min,laptot.time_sec);
#else
    laptot.time_min = laptot.time_tot / 60;
    laptot.time_sec = laptot.time_tot / 60;
    printf("The total time it took for the course to complete was %d minutes and %d seconds\n",
        laptot.time_min,laptot.time_sec);
#endif

    return 0;
}

UPDATE:

Thanks I'll definitely look more into this

It's an important concept for the future.

Using an array would have become more obvious if the lap count were larger, say, 100 instead of just 4.

When designing an algorithm, an important question to ask oneself is: Does my solution "scale" [up]?

A struct is like a form or [database] record. It brings all related things together. A form is a single piece of paper that has all information about a given topic (eg a tax form or personnel record).

Consider a simple personnel record:

typedef struct {
    char person_name[100];
    char person_street[100];
    char person_city[100];
    char person_state[2];
    char person_telno[10];
    int person_age;
    float person_salary;
} person;

This is like having a single page per person, and the employee file contains all such pages.

Without the struct idea, we'd need separate file folders for each of the above record "fields"

Names:

Smith, John
Jones, Fred
Miller, Mary

Streets:

123 Main St
235 Elm St
63 Oak Ave

Cities:

New York
Chicago
Los Angeles

Using the struct , our organization would look more like:

Smith, John     123 Main St     New York
Jones, Fred     235 Elm St      Chicago
Miller, Mary    63 Oak Ave      Los Angeles

In these real world terms, of course, this data organization seems obvious. But, when coding, particularly for things that are more abstract, it can sometimes be obscured by the complexity of the problem.

Being able to refine/reduce the code [often my ensuring that the data structures used are minimal and complete], can keep the code simple, clean, and robust.

This can even happen to experienced programmers. In a real commercial product I worked on, I found "parallel arrays" being used. I refactored the code to use an array of a new struct I created. I did this just to simplify/cleanup the code. In the process, I was able to uncover and fix at least five bugs that were latent and not obvious until the cleanup.

If I understand correctly what you want to do is something like this:

If the total time is less than 4 minutes then display a message

When you word it in English like this, it helps make it easier to translate into code. First we need to calculate the total time. You can do that with a single assignment:

int total = TotalSeconds1 + TotalSeconds2 + TotalSecond3 + TotalSeconds4;

Now we can write an if statement. One way to do this is to convert 4 minutes into seconds, but I'm too lazy to do this by hand, so I write it explicitly in the code:

if (total <= 4 * 60) {
    printf("You qualified!")
}

Of course, you can change the message here to suit your needs.

A few suggestions:

  1. Use meaningful variable names. For the most part, you do this very well. My only suggestion here is to use lap1 , lap2 , etc. instead of TotalSeconds1 .

  2. Learn about loops. I understand that you are new to programming. If you haven't yet learned about for and while loops, I'm sure they are coming up in the class. These are great tools that allow you to write less code for repeated tasks.

  3. Learn about arrays. In the same vein as #2, arrays allow you to store lists of data with a single variable. Whenever you find yourself naming variables with numbers on the end, you should most likely use an array instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM