帮助与基本的编程 [英] Help with basic programming
问题描述
这个问题我觉得是我多指针的理解,但在这里不用。我想创建一个在C系统程序进行计算,因此数学运算符值1值2。例如数学+ 1 2这会在屏幕上产生3。我有麻烦比较或求和的数字。以下是我迄今为止:
的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&string.h中GT;INT主(INT交流,字符* ARGS [])
{
INT总;
如果(的strcmp(* ++指定参数时,+)== 0)
{ }
的printf(总=值1);
如果(的strcmp(*指定参数时,X)== 0)
的printf(乘);
如果(的strcmp(*指定参数时,%)== 0)
的printf(模数);
如果(STRCMP(*指定参数时,/)== 0)
的printf(分);
返回0;
}
我可以做一个字符串比较,以获得运营商,但我有一个很难添加两个值。我曾尝试:
INT值1 =的atoi(* ++参数);
任何帮助将是AP preciated。
* ++ ARGS
既然你都做了pre-增量 ++
运营商具有较高的precedence比 *
使指针递增,以后你提领它这种情况下,你可能永远不会进入你居然打算的实际参数的来。
如果你有一个像输入
+ 1 2
我们有
ARGS [1] = +ARGS [2] = 1ARGS [3] = 2;
为什么不能随便进入的atoi(参数[2])
您可以不喜欢
INT主(INT ARGC,字符**参数)
{
如果(argc个!= 4)
{
的printf(arguements的数量较少的\\ n);
返回0;
} 否则如果((的strcmp(参数[1],+))== 0)
{
的printf(总和=%d个\\ N的atoi(参数[2])+与atoi(参数[3]));
} 返回0;
}
This issue I feel is more my understanding of pointers but here goes. I am suppose to create a system program in C that performs calculations as such math operator value1 value2. Example math + 1 2. This would produce 3 on the screen. I am having troubles comparing or summing the numbers. Here is what I have so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main( int ac, char* args[] )
{
int total;
if (strcmp(*++args,"+") == 0)
{
}
printf("Total= ", value1);
if (strcmp(*args,"x") == 0)
printf("multiply");
if (strcmp(*args,"%") == 0)
printf("modulus");
if (strcmp(*args,"/") == 0)
printf("divide");
return 0;
}
I can do a string compare to get the operator but am having a hard time adding the two values. I have tried:
int value1=atoi(*++args);
Any help would be appreciated.
*++args
Since you are doing a pre-increment ++
operator has higher precedence than *
so the pointer is incremented and later you are dereferencing it which case you might never get to access the arguement which you actually intend to.
If you have input like
+ 1 2
We have
args[1] = +
args[2] = 1
args[3] = 2;
Why can't just access atoi(args[2])
You can do something like
int main(int argc, char **args)
{
if(argc != 4)
{
printf("Fewer number of arguements\n");
return 0;
}
else if((strcmp(args[1],"+")) == 0)
{
printf("Sum = %d\n",atoi(args[2]) + atoi(args[3]));
}
return 0;
}
这篇关于帮助与基本的编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!