The program starts, but asks for input twice

I wrote the following program, but every time I run it, for loops do not work until I enter a different number. Then for loops are executed using the second number entered. Why is this happening? no one seems to have encountered this problem ... here is the program:

#include <stdio.h> #include <math.h> int main(void) { float limit; float count; float series1, series2; printf("Enter a limit for the series "); scanf ("%f", &limit); while (scanf ("%f", &limit) == 1) { for (series1 = 1, count = 2; count <= limit; count++) series1 += 1.0/count; printf ("\nThe sum of the first infinite series is %.4f", series1); for (series2 = 1, count = 2; count <= limit; count++) series2 += (1.0/count) * pow ((-1),(count - 1)); printf ("\nThe sum of the second infinite series is %.4f", series2); printf("\n\nEnter a limit for the series (q to quit) "); scanf ("%f", &limit); } return 0; } 
+4
source share
2 answers

Your problem is here:

 scanf ("%f", &limit); while (scanf ("%f", &limit) == 1) 

The while loop will execute this scanf every time it starts, so just lose the first scanf.

+4
source

When you run the while while while (scanf ("%f", &limit) == 1) , it starts scanf ("%f", &limit) == 1 again after you have already started it. Try setting the first scanf to print the variable and run the variable in a while loop.

0
source

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


All Articles