-2

I wrote a program that converts temperatures from Celsius to Fahrenheit. When I enter c, the code works as expected, but when I enter f, it gives me a random number:

#include <stdio.h>

int main (void){
    float f,c;

    printf("x=Ende c=Umrechnung c->f f=Umrechnung f->c:");
    if(scanf("c",&c)==c){
        printf("Grad Celisius =");
        scanf("%f",&c);
        f=(c*1.8)+32;
        printf("%.2f Grad Celisius sind %.2f Grad Fahreiheit\n",c,f);
    }
    else if(scanf("f",&f)==f){
        printf("Grad fahrenheit =");
        scanf("%f",&f);
        c=(f-32)/1.8;
        printf("%.2f Grad Fahrenheit sind %.2f Grad Fahrenheit",f,c);
    }
    return 0;
}

How can I fix my problem?

honk
  • 9,137
  • 11
  • 75
  • 83

1 Answers1

1

You didn't use the scanf() command properly. I modified your code a little bit and this works for me:

#include <stdio.h>

int main (void){
    float f,c;
    char ch;

    printf("x=Ende c=Umrechnung c->f f=Umrechnung f->c:");
    scanf(" %c", &ch);
    if(ch=='c'){
        printf("Grad Celsius =");
        scanf("%f",&c);
        f=(c*1.8)+32;
        printf("%.2f Grad Celsius sind %.2f Grad Fahrenheit\n",c,f);
    }
    else if(ch=='f'){
        printf("Grad Fahrenheit =");
        scanf("%f",&f);
        c=(f-32)/1.8;
        printf("%.2f Grad Fahrenheit sind %.2f Grad Celsius",f,c);
    }
    return 0;
}

Basically, you have read a character (ch) only once and compare it afterwards to the options that your program provides. Please note the space character in " %c" in the scanf() line. It might be needed so that the code works properly, as described here.

I guess that you also want to put a loop around your code, so that it makes sense to ask the user to enter an x in order to end the program. Currently the program terminates if you don't enter c or f. The program also terminates after one calculation has been done.

By the way, I also changed one Celsius to Fahrenheit in your last printf(). I think you confused the words there. I also changed Celisius to Celsius.

Community
  • 1
  • 1
honk
  • 9,137
  • 11
  • 75
  • 83
  • I'm glad to have been of help! Feel free to [accept my answer](http://meta.stackexchange.com/q/5234/294055) if you feel it was useful to you :) – honk Nov 07 '15 at 14:29