Reputation: 1
#include <stdio.h>
int main(void){
int iterations, counter;
double i = -1, j = 3, PI, calculate = 0;
printf("How many iterations?: ");
scanf("%d\n", &iterations);
counter = iterations;
while (counter > 0) {
calculate = calculate + (i/j);
i = i * (-1);
j += 2;
counter += -1;
}
PI = 4 * (1 + (calculate));
printf("PI = %f\n", PI);
return 0;
}
This program is in C. When I run it, it stays in the loop and will not give any output. If I stop the program it gives the correct result. What is wrong?
Upvotes: 0
Views: 60
Reputation: 5457
Change the scanf()
statement
scanf("%d\n", &iterations);
to this
scanf("%d", &iterations);
What difference does it make?
Putting any whitespace in the scanf()
format string makes it read and skip over all whitespace in the input. As long as you keep hitting enter ('\n'
) or space (' '
), it'll keep reading, until it reaches a non-whitespace character (or end of file
)
Additionally, it'd be good if you also check the return value of scanf()
if(scanf("%d", &iterations) == 1)
{
//continue...
}
else
{
//scan the number again
}
or even better, use a loop
while(scanf("%d", &iterations) != 1);
Upvotes: 4