【C语言】main函数模拟计算器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_41035588/article/details/83220903

模拟计算器

问题:使用main函数的参数,实现一个整数计算器,程序可以接受三个参数,第一个参数“-a”选项执行加法,“-s”选项执行减法,“-m”选项执行乘法,“-d”选项执行除法,后面两个参数为操作数。

思路: 首先应该清楚main函数里面至少有两个参数,argc和argv,要实现加减乘除,可以先将-a,-s,-m,-d所表示的运算用±*/来替换,通过判断输入的符号与-a,-s,-m,-d一一对应起来,调用的时候就更加方便了。然后根据得到的返回值加以在main函数中调用,得到想要的结果。比如:输入2+3,就应该得到2+3=5的结果,其他同理。

#include <stdio.h>
#include <Windows.h>
int Pc(int x,char *p,int y)
{
	if (p == "-a")
		return x+y;
    else if(p == "-s")
        return x-y;
    else if(p == "-m")
        return x*y;
	else if(p == "-d")
		return x/y;
	else 
		return -1;
}

int main(int argc,int argv)
{ 
     char a;
     char *p = &a;
     int x = 0;
     int y = 0;
     int ret = 0;
     scanf("%d%c%d",&x,&a,&y);
	 if(a == '+')
	 {
		 p = "-a";

	 }
	 else if(a == '-')
	 {
		 p = "-s";
	 }
	 else if(a == '*')
	 {
		 p ="-m";
	 }
	 else if(a == '/')
	 {
		 p = "-d";
	 }
	 else 
		 p = '\0';
	 ret = Pc(x,p,y);
	 printf("%d%c%d=%d\n",x,a,y,ret);
	 system("pause");
	 return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41035588/article/details/83220903