how to repeat a c program from the beginning and c

2019-08-01 11:22发布

i m new in programing. i've written a simple program. i want to repeat the program again and again and it can only exit when user wants to exit. here is my program

#include<stdio.h>
#include<conio.h>
main()
{
    char ch;
    int num1, num2, a, m, s, choice;
    float d;
    printf("\nEnter The First Number: ");
    scanf("%d", &num1);
    printf("\nEnter The Second Number: ");
    scanf("%d", &num2);
    a=num1+num2;
    m=num1*num2;
    s=num1-num2;
    d=(float)(num1/num2);
    printf("\nEnter Your Choice \nFor Addition Type A \nFor Multipication Type M \nFor Division Type D \nFor Substraction Type S : ");
    scanf(" %c", &ch);
    switch(ch)
        {
            case 'A': printf("\nThe Addition Of The Number Is= %d", a);
                break;
            case 'M': printf("\nThe Multipication Of The Numbers Is= %d", m);
                break;
            case 'S': printf("\nThe Substraction Of THe Numbers Is= %d", s);
                break;
            case 'D': printf("\nThe Division Of The Two Numbers Is= %f", d);
                break;
            default : printf("\nInvalid Entry");
                break;
        }
    printf("\nPress Any Key To Exit");
    getch();
    return 0;
}

and here is the output

"Enter The First Number: 10

Enter The Second Number: 10

Enter Your Choice

For Addition Type A

For Multipication Type M

For Division Type D

For Substraction Type S : A

The Addition Of The Number Is= 20

Press Any Key To Exit"

I want a line before the line Press Any Key To Exit

"If You Want To Calculate Again Press Y

or

Press Any Key To Exit"

when press Y then the program should start from the beginning.

How can i do this???

3条回答
beautiful°
2楼-- · 2019-08-01 12:10

wrap the code inside a do{} while() ?

char answer;
do{
printf("\nEnter The First Number: ");
scanf("%d", &num1);
printf("\nEnter The Second Number: ");
scanf("%d", &num2);
a=num1+num2;
m=num1*num2;
s=num1-num2;
d=(float)(num1/num2);
printf("\nEnter Your Choice \nFor Addition Type A \nFor Multipication Type M \nFor Division Type D \nFor Substraction Type S : ");
scanf(" %c", &ch);
switch(ch)
    {
        case 'A': printf("\nThe Addition Of The Number Is= %d", a);
            break;
        case 'M': printf("\nThe Multipication Of The Numbers Is= %d", m);
            break;
        case 'S': printf("\nThe Substraction Of THe Numbers Is= %d", s);
            break;
        case 'D': printf("\nThe Division Of The Two Numbers Is= %f", d);
            break;
        default : printf("\nInvalid Entry");
            break;
    }
printf("\nPress Y to continue. Press any Key To Exit");
scanf(" %c",&answer); // dont forget type &
}
while(answer == 'y' || answer == 'Y');

Declare a variable, let's say answer, which will store the user answer when you ask for "Press Y to continue. Press any Key To Exit". Check to see what value has that variable. If is 'y' or 'Y', the loop will repeat. If the user pressed other key, the loop is over.

查看更多
Rolldiameter
3楼-- · 2019-08-01 12:13

You can also use recursion, which is often used in more functional oriented programming languages.

Pseudo-code:

myfunction = do 
    ...
    b <- somethingtodo
    ...
    if b
      then myfunction 
      else return ()

Relative to Jens's solution, it would look like:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main (void)
{
    char choice;
    int num1, num2, cont;
    printf("Enter the first number: ");
    scanf("%d", &num1);
    getchar ();
    printf("Enter the second number: ");
    scanf("%d", &num2);
    getchar ();
    printf("A - addition\n");
    printf("S - subtraction\n");
    printf("M - multiplication\n");
    printf("D - division\n");
    printf("[ASMD]? ");
    choice = (char)toupper(getchar());
    getchar (); 
    printf("\n");
    switch(choice)
    {
        case 'A':
            printf("%d + %d = %d", num1, num2, num1 + num2);
            break;
        case 'S':
            printf("%d - %d = %d", num1, num2, num1 - num2);
            break;
        case 'M':
            printf("%d * %d = %d", num1, num2, num1 * num2);
            break;
        case 'D':
            if (num2 == 0)
                fprintf(stderr, "The divisor can not be zero");
            else
            {
                printf("%d / %d = %f", num1, num2, (double)num1 / num2);
            }
            break;
        default :
            fprintf(stderr, "Invalid entry");
            break;
    }
    printf("\n");
    for (;;)
    {
      printf("Continue [YN]? ");
      cont = toupper(getchar());
      getchar ();
      if (cont == 'Y')
          return main(); // the difference.
      else if (cont == 'N')
          return EXIT_SUCCESS;
    }
}
查看更多
聊天终结者
4楼-- · 2019-08-01 12:14

I would move the calculation stuff in it's own function and then use while() in main.

I have tried to fix other problems as well (this solution only uses standard C functions).

#include <stdio.h> // puts, printf, fprintf, scanf, getchar, stderr, EOF
#include <stdlib.h> // exit, EXIT_SUCCESS, EXIT_FAILURE
#include <ctype.h> // toupper

char fail_on_eof (int c)
{
    if (c == EOF)
        exit (EXIT_FAILURE);
    // In case of fail_on_eof (scanf (...)) the return value of this this
    // function is not useful
    // scanf () returns the number of chars read or EOF
    // getchar () returns a char or EOF
    return (char) c;
}

void skip_to_next_line (void)
{
    char c;
    do
    {
        c = fail_on_eof (getchar ());
    } while (c != '\n');
}

char read_upcase_char_line (char* prompt)
{
    char c;
    printf ("%s ", prompt);
    c = fail_on_eof (toupper (getchar ()));
    skip_to_next_line ();
    return c;
}

int read_num_line (char* prompt)
{
    int num;
    printf ("%s ", prompt);
    fail_on_eof (scanf ("%d", &num));
    skip_to_next_line ();
    return num;
}

int calculate (void)
{
    char choice;
    int num1, num2, cont;
    num1 = read_num_line ("Enter the first number:");
    num2 = read_num_line ("Enter the second number:");
    puts("A - addition");
    puts("S - subtraction");
    puts("M - multiplication");
    puts("D - division");
    choice = read_upcase_char_line ("[ASMD]?");
    puts("");
    switch(choice)
    {
        case 'A':
            printf("%d + %d = %d", num1, num2, num1 + num2);
            break;
        case 'S':
            printf("%d - %d = %d", num1, num2, num1 - num2);
            break;
        case 'M':
            printf("%d * %d = %d", num1, num2, num1 * num2);
            break;
        case 'D':
            if (num2 == 0)
                // Better use stderr for error messages
                fprintf(stderr, "The divisor can not be zero");
            else
            {
                printf("%d / %d = %f", num1, num2, (double)num1 / num2);
            }
            break;
        default :
            // Better use stderr for error messages
            fprintf(stderr, "Invalid entry");
            break;
    }
    printf("\n");
    for (;;)
    {
      cont = read_upcase_char_line ("Continue [YN]?");
      if (cont == 'Y')
          return -1;
      else if (cont == 'N')
          return 0;
    }
}

int main(void)
{
    while (calculate ());
    return EXIT_SUCCESS; // Use this constant to avoid platform specific issues with the return code
}
查看更多
登录 后发表回答