这个程序首先分叉然后由execlp运行,它的调用程序传递两个数字,一个幂和一个基数。
int main(int argc, char *argv[])
{
int pid = getpid();
printf("Calculator Process[%d]: started\n",pid);
double base, power;
sscanf(argv[1],"%d",&base);
sscanf(argv[2],"%d",&power);
double number = pow(base,power);
printf("Calculator Process[%d]: %d ^^ %d == %d\n",pid,base,power,number);
printf("Calculator Process[%d]: exiting\n",pid);
return 1;
}
让我说我进入基地3,力量5.这就是我得到的:
base = 4263 -- this also happens to be the PID. power = -1 raised to power: 714477568
致电热线:
execlp("./calculator","./calculator",argv[1],argv[2],(char*)0);
当我打印argvs时,我得到它们的值(作为char *,但是转换失败)。
为什么我无法正确读入值的任何想法?
答案 0 :(得分:9)
读取双倍:
double base, power;
sscanf(argv[1],"%lf",&base);
sscanf(argv[2],"%lf",&power);
或扫描成整数:
int base, power;
sscanf(argv[1],"%d",&base);
sscanf(argv[2],"%d",&power);
答案 1 :(得分:0)
快速调整代码应该这样做:
int main(int argc, char *argv[])
{
int pid = getpid();
printf("Calculator Process[%d]: started\n",pid);
double base, power;
base = atof(argv[1]);
power = atof(argv[2]);
double number = pow(base,power);
printf("Calculator Process[%d]: %f ^^ %f == %f\n",pid,base,power,number);
printf("Calculator Process[%d]: exiting\n",pid);
return 1;
}
atof()
%f
,否则它们将无法在输出中显示!