Home > OS >  My program in C works all fine, but at the very end when I try to create a loop so it keeps repeatin
My program in C works all fine, but at the very end when I try to create a loop so it keeps repeatin

Time:10-08

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define pi 3.14159265

int main()
{
    int n;
    int fact=1;
    int i;
    char repeat;
    do{
    //part a
    printf("Please input a positive whole number value to be stored as 'n': ");
    scanf("%d",&n);
    while(n<0){
        printf("Improper value of n. Please input a positive whole number value to be stored as 'n': ");
        scanf("%d",&n);
    }
    //part b
    if (n>0){
        printf("n is now %d\n",n);
        for(i=1;i<=n;i  ){
            fact=fact*i;
        }
        //printf("The factorial of %d is %d.\n",n,fact);
    }
    else{
        printf("The factorial of 0 is 1.\n");
    }
    //part c
    double approx = (pow((double)n,n)*exp(-n))*sqrt(((2*n) (1/3))*pi);
    //printf("Approx is %lf",approx);
    //part d
    printf("%d! equals approximately %lf.\n",n,approx);
    printf("%d! is %d accurately.\n",n,fact);
    //part e
    double perror=((fact-approx)/(fact))*100;
    printf("The approximate value is off by %lf%%\n",perror);
    //part f
    printf("Would you like to restart with another value? Respond y or n: ");
    scanf("%c",&repeat);
    } while(repeat=='y');
    /*I was going to have the program restart if the user input "y" at the end of the program but I can't
    figure out why it isn't working.*/

    return 0;
}

I'm still very new to programming in C and am still learning the basics so any explanations are appreciated. The only part that I have left to and haven't been able to figure out is as to why the do...while loop isn't working at the beginning and end of the code.

CodePudding user response:

scanf("%c",&repeat);

You need a space before %c in order to consume the newline left by previous calls to scanf:

scanf(" %c",&repeat);

From https://linux.die.net/man/3/scanf:

Conversions

c

Matches a sequence of characters whose length is specified by the maximum field width (default 1); the next pointer must be a pointer to char, and there must be enough room for all the characters (no terminating null byte is added). The usual skip of leading white space is suppressed. To skip white space first, use an explicit space in the format.

Also, never trust the user and always initialize the variables before using scanf, otherwise you can end up reading uninitialized values (garbage) if it fails:

char repeat;

should be

char repeat = 'n';

or at least check the result of scanf and fill the variable with proper default values:

char repeat;
...
if (scanf(" %c",&repeat) != 1)
{
    repeat = 'n';
}
  • Related