Keyur Maru
Keyur Maru

Reputation: 11

How to fix the error of type-mismatch and trailing spaces in C

This was my school assignment and the feedback from the professor says violates the rule of type-mismatch and also avoid trailing spaces. I couldn't still pinpoint the exact problem.

#include<stdio.h>
#define SECS_PER_HOUR 3600 //1 hour = 60mins * 60 secs = 3600 secs
#define METERS_PER_MILE 1600 
int main()
{
    double distance, time, speedmph, speedmps;

    scanf("%lf", &distance);
    scanf("%lf", &time);

    speedmph = distance / time;
    speedmps = (speedmph * METERS_PER_MILE) / SECS_PER_HOUR;

    printf("\nThe speed is %.2f miles per hour. \n", speedmph);
    printf("The speed is %.2f meters per second. \n\n", speedmps);

    main();
}

Upvotes: 0

Views: 307

Answers (1)

the busybee
the busybee

Reputation: 12653

Most probably your code should look like this:

#include<stdio.h>

#define SECS_PER_HOUR 3600 // 1 hour = 60mins * 60 secs = 3600 secs
#define METERS_PER_MILE 1600

int main(void)
{
    for (;;)
    {
        double distance;
        double time;
        double speedmph;
        double speedmps;

        scanf("%lf", &distance);
        scanf("%lf", &time);

        speedmph = distance / time;
        speedmps = (speedmph * METERS_PER_MILE) / SECS_PER_HOUR;

        printf("\nThe speed is %.2lf miles per hour.\n", speedmph);
        printf("The speed is %.2lf meters per second.\n\n", speedmps);
    }
}

Changes are:

  1. Separate unrelated lines by one empty line.
  2. Indent the source to reflect the structure.
  3. Define each variable in its own line. This improves readability and is good habit to avoid problems if you define pointers in other programs.
  4. Concerning type mismatch: Change %.2f into %.2lf to match the double. However, as @user3386109 wrote, for printf() its the same. If there were some float it would be casted to a double.
  5. Concerning trailing spaces: Remove blanks before \n.
  6. Add endless loop to avoid stack overflow (no pun intended) if the compiler does not realize tail recursion.

Upvotes: 2

Related Questions