-1

So I'm trying to make a simple temperature converter. All looks fine to me but I don't know why the scan input is not being recognised. Thanks for your time.

    #include <stdio.h>
    exercise1(){
        float a;
        char tem;
        printf("--- Temperature Converter ---\n");
        printf("Please enter a temperature: ");
        scanf("%f", &a);
        printf("\nWould you like to convert to Celsius or Fahrenheit? (c or f)");
        scanf("%c", &tem); getchar();
        if (tem == 'c'){
            a = ((float)a-32) * 5.0f/9.0f;
            printf("\nYour temperature is %g\n", &a);
        }
        else if (tem == 'f'){
            a = (float)a * 9.0f/5.0f + 32;
            printf("\nYour temperature is %g\n", &a);
        }
        else
            printf("\nPlease enter a valid conversion type!\n");
        }
    }
Mike Dunlavey
  • 40,059
  • 14
  • 91
  • 135
Abdo
  • 9
  • 2
  • 2
    `printf("\nYour temperature is %g\n", &a);` remove `&` --> `printf("\nYour temperature is %g\n", a);` – BLUEPIXY Feb 20 '17 at 17:04
  • Probably because you are calling `getchar` right after it. By the way, with `float a`, there is no need for `(float)a` later in the code (but that is purely semantic). – goodvibration Feb 20 '17 at 17:04
  • Thanks, I combined all of the answers and got it working. – Abdo Feb 21 '17 at 14:16

1 Answers1

1

The problem with the scanf() was when you entered a whitespace to finish inserting the temperature, that whitespace would then be inserted to tem. In order to prevent it, use the getchar() before the scanf(), as shown below.

NOTE: when checking the answers given to you, I saw one suggesting you use " %c" instead of "%c". This is a good idea, and it works well. Note that if you prefer this solution, you should not use getchar()

In addition, there were few more mistakes that I found: 1. When using printf(), you should not send &a, but send a instead. printf() does not require a pointer, but a variable. (Notice the warning while compiling) 2. Use %f to scan floats, not %g 3. You have used too much } after the last else (only one is needed, to close the function)

#include <stdio.h>
void main(){
        float a;
        char tem;
        printf("--- Temperature Converter ---\n");
        printf("Please enter a temperature: ");
        scanf("%f", &a);
        printf("\nWould you like to convert to Celsius or Fahrenheit? (c or f)");
        getchar();
        scanf("%c", &tem);
        if (tem == 'c'){
                a = ((float)a-32) * 5.0f/9.0f;
                printf("\nYour temperature is %f\n", a);
        }
        else if (tem == 'f'){
                a = (float)a * 9.0f/5.0f + 32;
                printf("\nYour temperature is %f\n", a);
        }
        else
                printf("\nPlease enter a valid conversion type!\n");}
Dan Sheinin
  • 59
  • 10