我是编程新手。 我写了一个简单的程序。 我想一次又一次地重复这个程序,它只能在用户想要退出时退出。 这是我的程序
#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;
}
这是输出
"输入第一个数字:10
输入第二个数字:10
输入您的选择
对于添加类型 A
对于 M 型乘法
对于分区类型 D
对于减法类型 S : A
数字相加=20
按任意键退出”
我想在 Press Any Key To Exit 行之前加一行
"如果您想再次计算,请按 Y
或
按任意键退出”
当按下 Y 时,程序应该从头开始。
我该怎么做???
最佳答案
将代码包装在 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');
声明一个变量,比方说 answer,当您要求“按 Y 继续。按任意键退出”时,它将存储用户答案。检查该变量的值。如果是 'y' 或 'Y',循环将重复。如果用户按下其他键,则循环结束。
关于c - 如何从头开始重复 c 程序并清理屏幕和第一个输入值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25831801/