-3

I think due to while loop the fahr variable is changing everytime the loop is executed and because of that the variable conv is changing. But I don’t know how to fix it. So can anyone please help me out?

#include<stdio.h>
main() {
    int n,step;
    float fahr,cel,conv;
    conv=fahr+(n*step);

    printf("This program makes 'n' number of list for fahrenheit to celcius converted numbers.\n");

    printf("Please enter the number that is 'n'- \n");

    scanf("%d",&n);
    printf("\nPlease enter the fahrenheit value- \n");

    scanf("%f",&fahr);
    printf("\nPlease enter step count- \n");

    scanf("%d", &step);
    printf("\nFahrenheit\tCelcius\n");

    cel=((float)5/(float)9)*(fahr-32);

        while(fahr<=conv){
            printf("%f\t%f\n",fahr,cel);
            fahr=fahr+step;
        };
}

EDIT -

So heres the updated version I wrote. This version can do two types of conversion now and it can restart the program. @DavidC.Rankin can you please check this one and suggest me what should I change? I didn't use fputs because I don't know how it works. Thanks a lot.

#include <stdio.h>
int main()
{
    int n, step, i, conv ;

    double fahr, cel ;

    start:

    puts("\nThis program can make 'n' number of lists of two type of conversions-\n\n(1) Fahrenheit to Celcius conversion\n\n(2) Celcius to Fahrenheit conversion\n");

    puts("Which type of conversion would you like to use?\n(please enter the number)\n");

    scanf("%d",&i);




    if(i==1){

        puts("\nThis program makes 'n' number of list for \n'Fahrenheit to Celcius converted numbers'\nstarting from the given Fahrenheit value.\n");

        puts("Please enter the value of 'n'- ");

        scanf("%d", &n);

        puts("\nPlease enter the Fahrenheit value- ");

        scanf("%lf", &fahr);

        puts("\nPlease enter step count- ");

        scanf("%d", &step);

        puts("\n\tFahrenheit\tCelcius"
             "\n\t----------\t-------");

        conv = fahr + (n * step);

        cel = (5. / 9.) * (fahr - 32);

        while (fahr <= conv)
        {
            printf("\t%lf\t%lf\n",fahr,cel);

            fahr = fahr + step;

            cel = (5. / 9.) * (fahr - 32);
        };

        goto again;
    }




    else if(i==2){

        puts("\nThis program makes 'n' number of list for \n'Celcius to Fahrenheit converted numbers'\nstarting from the given Celcius value.\n");

        puts("Please enter the value of 'n'- ");

        scanf("%d", &n);

        puts("\nPlease enter the Celcius value- ");

        scanf("%lf", &cel);

        puts("\nPlease enter step count- ");

        scanf("%d", &step);

        puts("\n\tCelcius\tFahrenheit"
             "\n\t-------\t----------");

        conv = cel + (n * step);

        fahr = ((9. * cel) / 5.) + 32;

        while (cel <= conv)
        {
        printf("\t%lf\t%lf\n",cel,fahr);

        cel = cel + step;

        fahr = ((9. * cel) / 5.) + 32;
        };

        goto again;
    }




    else{

        puts("Invalid Input! Please try again\n\n\n\n");

        goto start;

    };




    again:

    puts("Would you like to restart the program?\n"
         "\tyes=1    no=0\n");

    scanf("%d",&i);

    if(i == 1){

        goto start;

    }

    else if(i == 0){

        puts("The program has ended.");

    }

    else{

        puts("Wrong Input!\n");

        goto again;

    };
}

Junnun Karim
  • 23
  • 1
  • 5
  • Beware of using uninitialized variables for calculations inside main() function (or other functions) in C programs like you did in your 5th line. Uninitialized variables store garbage values by default. – Guy_g23 Mar 28 '20 at 09:12
  • Oh I didn’t knew that thanks – Junnun Karim Mar 28 '20 at 16:48

2 Answers2

1

you are using uninitialized variables in this line conv=fahr+(n*step);

this line should be here:

main() {
    int n, step;
    float fahr, cel, conv;

    printf("This program makes 'n' number of list for fahrenheit to celcius converted numbers.\n");

    printf("Please enter the number that is 'n'- \n");

    scanf("%d", &n);
    printf("\nPlease enter the fahrenheit value- \n");

    scanf("%f", &fahr);
    printf("\nPlease enter step count- \n");

    scanf("%d", &step);
    printf("\nFahrenheit\tCelcius\n");
    conv = fahr + (n * step);

    cel = ((float)5 / (float)9) * (fahr - 32);

    while (fahr <= conv) {
        printf("%f\t%f\n", fahr, cel);
        fahr = fahr + step;
        cel = 5./9. * (fahr - 32);
    };
}

also as @David C. Rankin said in comment, you should add cel = 5./9. * (fahr - 32) as the last expression in the while loop. Otherwise cel is never updated. and so while fahr changes, you will have same value in cel.

also pay attention to the way of scanning data which @David C. Rankin said in comment.use this instead of scanf("%d",&n);

(if (scanf("%d", &n) != 1) 
{ 
fputs ("error: invalid integer value.\n", stderr); 
return 1;
}

for checking success of taking input.

hanie
  • 1,863
  • 3
  • 9
  • 19
1

You have two-primary problems and a number of minor issue. @hanie has already pointed out where you used variables with automatic storage duration while their values were indeterminate in:

conv=fahr+(n*step);

The second issue that will prevent you from ever getting any interesting output is you fail to update the value of cel within your loop. That means that the same value for cel will be output no matter what the value of fahr is. You need to calculate a new cel after you update the value for fahr, e.g.

    cel = 5./9. * (fahr - 32);

    while (fahr <= conv) {
        printf ("% 2g\t\t% 8.2f\n", fahr, cel);
        fahr = fahr + step;
        cel = 5./9. * (fahr - 32);      /* you must update cel within the loop */
    }

You invite Undefined Behavior by failing to validate your user input succeeds. You cannot use any user-input function correctly unless you check the return. For scanf the return is the number of successful conversions that took place. In each case you are attempting 1-conversion, so you must check the return of each call to scanf to determine if it is 1 indicating a successful conversion. Otherwise, a matching failure will leave the character causing failure unread in stdin resulting in all of your variables having indeterminate values even after the attempted inputs invoking undefined behavior. Take the time and check the return, for EVERY user-input.

Putting it altogether and eliminating the unnecessary casts and changing type float to double, and eliminating printf for all outputs where no conversion is required, you would have:

#include<stdio.h>

int main (void) {

    int n, step;
    double fahr, cel, conv;

    /* there is no conversion -- printf isn't needed, use puts */
    puts ("This program makes 'n' number of list for fahrenheit "
            "to celcius converted numbers.\n");

    puts ("Please enter the number that is 'n'-");
    if (scanf ("%d", &n) != 1) {        /* validate EVERY user-input */
        fputs ("error: invalid integer input.\n", stderr);
        return 1;
    }

    puts ("\nPlease enter the fahrenheit value-");
    if (scanf ("%lf", &fahr) != 1) {    /* validate EVERY user-input */
        fputs ("error: invalid double input.\n", stderr);
        return 1;
    }

    puts ("\nPlease enter step count-");
    if (scanf ("%d", &step) != 1) {     /* validate EVERY user-input */
        fputs ("error: invalid integer input.\n", stderr);
        return 1;
    }

    conv = fahr + (n * step);

    puts ("\nFahrenheit       Celcius\n"
            "-----------      --------");

    cel = 5./9. * (fahr - 32);

    while (fahr <= conv) {
        printf ("% 2g\t\t% 8.2f\n", fahr, cel);
        fahr = fahr + step;
        cel = 5./9. * (fahr - 32);      /* you must update cel within the loop */
    }
}

(note: a good compiler with make the printf -> puts optimization for you, but show an understanding of how to handle output in C by using the correct function where no value conversion is required)

Example Use/Output

A simple example listing all values for Fahrenheit from 20 t0 40 by 1 would result in:

$ ./bin/cf
This program makes 'n' number of list for fahrenheit to celcius converted numbers.

Please enter the number that is 'n'-
20

Please enter the fahrenheit value-
20

Please enter step count-
1

Fahrenheit       Celcius
-----------      --------
 20                -6.67
 21                -6.11
 22                -5.56
 23                -5.00
 24                -4.44
 25                -3.89
 26                -3.33
 27                -2.78
 28                -2.22
 29                -1.67
 30                -1.11
 31                -0.56
 32                 0.00
 33                 0.56
 34                 1.11
 35                 1.67
 36                 2.22
 37                 2.78
 38                 3.33
 39                 3.89
 40                 4.44

Let me know if you have further questions.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
  • Thanks a lot for the explanations. But can you please explain how do fputs work and why did you use "fputs ("error: invalid double input.\n", stderr);"? I searched it but since I'm a beginner, I didn’t understand it. Btw I'm using book "The C programming language" by Dennis Ritchie for learning C. @DavidC.Rankin – Junnun Karim Mar 29 '20 at 16:43
  • You use the variadic function `printf` (or `fprintf`) when you require a **conversion** in your output. such as `int apples = 5; printf ("you have %d apples.\n", apples);` If you have no conversion in your output, you simply need to output a character string. That is what `puts()` and `fputs()` do. `puts()` writes to `stdout` and adds a `'\n'` at the end. `fputs()` can write to any file stream, and since I am describing an error with `"error: invalid double input.\n"` I want that output on`stderr` instead of `stdout`. So, conversion -- use `printf/fprintf`, if none use `puts/fputs`. – David C. Rankin Mar 29 '20 at 21:28
  • See the [man 3 puts](http://man7.org/linux/man-pages/man3/puts.3.html) for details on the function usage. (always check the man-page if you have any questions about a function) Also, what version of `"The C programming language"` are you using? The earlier version are woefully outdated, but are still valuable on the fundamentals of the language. If your version doesn't discuss C11 (or heaven forbid doesn't mention C99) you are using a very old version. – David C. Rankin Mar 29 '20 at 21:31
  • I'm using 2nd edition of "The C Programming language" which uses ANSI C standard ( C89 ). I only have that book so I have to first learn from it. Thanks again for using your time to help me @DavidC.Rankin – Junnun Karim Mar 30 '20 at 07:50
  • Still a good book, Ritchie was one of the original authors of C. Just understand there have been a number of additions to the C language since version 2 came out. [**The Definitive C++ Book Guide and List **](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list?s=1|10.4972) has some recommendations (and more importantly recommendations on which books to avoid) – David C. Rankin Mar 30 '20 at 15:47
  • Thanks I will look into it. – Junnun Karim Mar 31 '20 at 10:19