要求用户重复该程序或退出C

时间:2016-01-22 07:57:11

标签: c printf

在这个要求用户输入两个数字的非常基本的程序中,然后程序将这些数字加在一起。我想最后问用户他/她是否想再次重复该程序或退出程序!例如,如果他/她按y,程序将重新输入用户输入两个数字,否则程序将被关闭。怎么做?

main(){
float x,y,sum;
printf ("Enter the first number:");
scanf ("%f",&x);
printf ("Enter the second number:");
scanf ("%f",&y);
sum=x+y;
printf ("The total number is:%f",sum);
}

3 个答案:

答案 0 :(得分:4)

main(){
    float x,y,sum;
    char ch;

    do{
    printf ("Enter the first number:");
    scanf ("%f",&x);
    printf ("Enter the second number:");
    scanf ("%f",&y);
    sum=x+y;
    printf ("The total number is:%f",sum);
    printf ("Do you want to continue: y/n");
    scanf (" %c", &ch);
    } while(ch == 'y');
    }

或者你也可以试试这个:

main(){
    float x,y,sum;
    char ch;

    do{
    printf ("Enter the first number:");
    scanf ("%f",&x);
    printf ("Enter the second number:");
    scanf ("%f",&y);
    sum=x+y;
    printf ("The total number is:%f",sum);
    printf ("Do you want to continue: y/n");
    ch = getchar();
    getchar();
    } while(ch == 'y');
    }

答案 1 :(得分:1)

int main(void) {
float x,y,sum;
char ch;
do {
printf ("Enter the first number:");
scanf ("%f",&x);
printf ("Enter the second number:");
scanf ("%f",&y);
sum=x+y;
printf ("The total number is:%f\n",sum);
printf ("Do you want to repeat the operation Y/N: ");
scanf (" %c", &ch);
}
while (ch == 'y' || ch == 'Y');
}

这使用do-while循环。它将一直持续到while的{​​{1}}中的条件将返回false。

简单来说,只要用户输入do-whileyY循环就会返回true。因此,它将继续。

查看while循环的this示例和教程。

答案 2 :(得分:-1)

[[在此程序中,我使用了'goto'语句,因为如果我使用do while循环,那么如果我输入不带“ Y或y”的任何内容,则程序将关闭。为避免此问题,我使用了'goto'语句。{ {3}}

#include<stdio.h>
int main(){
int x, y, sum;
char ch;
print:
    printf ("Enter the first number:");
    scanf ("%d",&x);
    printf ("Enter the second number:");
    scanf ("%d",&y);
    sum=x+y;
    printf ("\nThe total number is:%d\n",sum);
again:
    printf ("\n\t\t\t\t\tDo you want to repeat the operation(Y/N): ");
    scanf (" %c", &ch);

    if(ch == 'y' || ch == 'Y'){
        goto print;
    }
    else if(ch == 'n' || ch == 'N'){
        return 0;
    }
    else{
        printf("\n\t\t\t\t\tPlease enter Yes or NO.\n");
        goto again;
    }
   return 0;

}