-1
我想打印由算术计算生成的不同打印语句以及3个不同的错误(错误的格式,除以零和错误的操作符)。我想从基于子函数的退出值的主函数打印
我负责的,现在的问题是,无论输入是什么,程序从出口(50)打印出“错误陈述”,即使格式是正确的......
这里我的代码:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int childFunction(char *string);
char input;
char *string = &input;
int status;
int pid;
int main (void)
{
printf("This program makes simple arithmetics\n");
while(1)
{
printf("Enter an arithmetic statement, e.g., 34 + 132\n");
input = scanf("%s",&input);
pid = fork();
if (pid == -1) // Error creating child process
{
perror("Impossible to fork\n");
exit(0);
}
else if (pid == 0) // Child process
childFunction(&input);
else
{
if (pid > 0) // Parent process
{
printf("Created a child to make your operation, waiting\n");
wait(&status);
sleep(2);
if (WEXITSTATUS(status) == 50)
printf("Wrong Statement\n\n");
else if (WEXITSTATUS(status) == 100)
printf("Division by zero\n\n");
else
if (WEXITSTATUS(status) == 200)
printf("Wrong operator\n\n");
}
}
}
return (0);
}
int childFunction(char *string)
{
int n1, n2;
char op;
float div = n1/n2;
printf("I am a child working for my parent\n\n");
sscanf(string, "%d %c %d", &n1, &op, &n2);
if ((sscanf(&input,"%d %c %d", &n1, &op, &n2)) != 3)
exit(50);
if (op == '/' && n2 == 0)
exit(100);
switch (op)
{
case '+':
printf("\n%d %c %d = %d", n1, op, n2, n1+n2);
case '-':
printf("\n%d %c %d = %d", n1, op, n2, n1-n2);
case '/':
printf("\n%d %c %d = %f", n1, op, n2, div);
case '*':
printf("\n%d %c %d = %d", n1, op, n2, n1*n2);
default:
exit(200);
}
exit(0);
sleep(1);
}
试过了......还没有工作。 – user4062234 2014-11-02 18:58:59