用c语言写一个只有加减乘除的计算器,它可以多次输入,直到用户想结束再退出程序。
#include <stdio.h>//望采纳!!!
int main (void)
{
double a, b;
char ch,yn;
do{
fflush(stdin,NULL);
printf ("请输入运算式子:");
scanf ("%lf%c%lf", &a, &ch, &b);
switch (ch)
{
case '+':
{
printf ("%lf %c %lf = %lf\n", a, ch, b, a + b);
break;
}
case '-':
{
printf ("%lf %c %lf = %lf\n", a, ch, b, a - b);
break;
}
case '/':
{
printf ("%lf %c %lf = %lf\n", a, ch, b, a / b);
break;
}
case '*':
{
printf ("%lf %c %lf = %lf\n", a, ch, b, a * b);
break;
}
default:
{
printf("式子输入错误!请以(数1+数2)这种格式输入!");
}
}
fflush(stdin,NULL);
printf("计算完毕!是否再次使用?y/n:");
scanf ("%c",&yn);
if (yn=='y' || yn=='Y')
{
system("cls");
printf ("欢迎再次使用\n\n");
continue;
}
printf("感谢使用本计算器!本次服务到此结束!\n");
break;
}while (1);
}
要定义函数四个,然后再调用
#include <math.h>
int main(void)
{
float data1,data2;
char op;
char reply;
do{
printf("Please enter the expression:\n");
scanf("%f %c%f",&data1,&op,&data2);//%c前有一空格
switch(op)
{
case '+':printf("%f+%f=%f\n",data1,data2,data1+data2);break;
case '-':printf("%f-%f=%f\n",data1,data2,data1-data2);break;
case '*':printf("%f*%f=%f\n",data1,data2,data1*data2);break;
case '/':if(fabs(data2)<=1e-7)
{
printf("Division by zero!\n");
}
else
{
printf("%f/%f=%f\n",data1,data2,data1/data2);
}
break;
default:printf("Unknown operator!\n");
}
printf("Do you want to continue(Y/N or y/n?)");
scanf(" %c",&reply);//%c前有一空格
}
while(reply=='Y'||reply=='y');
printf("Program is over!\n");
return 0;
}
注意一定要有空格,否则程序无法正常运行
int main()
{
char ch;
do
{
double i, j;
int c;
printf("\n\n 四则运算 \n\n");
printf("!请说明你需要的运算方式\n");
printf("!乘法请按 1\n");
printf("!除法情按 2\n");
printf("!加法请按 3\n");
printf("!减法请按 4\n");
LOOP:scanf("%d", &c);
if(c <= 4)
{
printf("请输入数字,中间以空格隔开\n");
switch(c)
{
case 1:
{
scanf("%lf", &i);
scanf("%lf", &j);
printf("结果为 %lf\n", i+j);
break;
}
case 2:
{
printf("第二个数字为除数\n");
scanf("%lf", &i);
scanf("%lf", &j);
if (j==0)
{
printf("除数不能为零\n");
break;
}
else
{
printf("结果为 %lf\n", i/j);
break;
}
}
case 3:
{
scanf("%lf", &i);
scanf("%lf", &j);
printf("结果为 %lf\n", i+j);
break;
}
case 4:
{
printf("第二个数字为减数\n");
scanf("%lf", &i);
scanf("%lf", &j);
printf("结果为 %lf\n", i-j);
break;
}
}
printf("是否继续\n");
printf("继续按y\n");
scanf(" %c", &ch);
}
else
{
printf("请重新输入一到四\n");
goto LOOP;
}
} while ('y'==ch||'Y'==ch);
return 0;
}