C simple program not working

Hello to all! I am trying to learn the C language and have this problem:

The sample code from the book works the way it should work:

#include <stdio.h> /*         fahr = 0, 20, ..., 300 */ main() { int fahr, celsius; int lower, upper, step; lower = 0; /*     */ upper = 300; /*   */ step = 20; /*  */ fahr = lower; while (fahr <= upper) { celsius = 5 * (fahr-32) / 9; printf("%d\t%d\n", fahr, celsius); fahr = fahr + step; } } 

Output:

0-17
20 -6
40 4
60 15
80 26
100 37
120 48
140 60
160 71
180 82
200 93
220 104
240 115
260 126
280 137
300,148

But the code I wrote does nothing !:

 #include <stdio.h> main() { int fahr, celsius, lower, upper, step; printf("Enter lower temperature:"); scanf("%d", &lower); printf("Enter upper limit:"); scanf("%d", &lower); printf("Enter step:"); scanf("%d", &lower); fahr = lower; while (fahr <= upper) { celsius = 5 * (fahr-32) / 9; printf("%d\t%d\n", fahr, celsius); fahr = fahr + step; } } 

Output:

$ gcc fahr.c -o fahr.out
$. / fahr.out
Enter a lower temperature: 0
Enter upper limit: 300
Enter step: 20
$

What's wrong?

+6
source share
5 answers

All of your scanners read the variable below.

 scanf("%d", &lower); 

This is very typical when you copy and paste sections of code. Welcome to C, we hope you love it just like everyone else.

+3
source

Change this part →

  printf("Enter upper limit:"); scanf("%d", &lower); printf("Enter step:"); scanf("%d", &lower); 

to

  printf("Enter upper limit:"); scanf("%d", &upper); printf("Enter step:"); scanf("%d", &step); 
+5
source

you &lower three times. Check scanf value lower , upper and step

+2
source

Your code

  printf("Enter upper limit:"); scanf("%d", &lower); 

he should be

  printf("Enter upper limit:"); scanf("%d", &upper); 

and similarly

 printf("Enter step:"); scanf("%d", &step); 
+1
source

The error is here:

 printf("Enter upper limit:"); scanf("%d", &lower); printf("Enter step:"); scanf("%d", &lower); 

Change both scanf options to the following code:

 scanf("%d", &upper); scanf("%d", &step); 

Do not copy the paste code if you want to avoid such errors.

0
source

Source: https://habr.com/ru/post/948893/


All Articles