我在这个问题上已经有一段时间了。我将打印出双“生成”,它显然是由用户输入的数字,但由于某种原因,它的行为并不相同。这是在Unix btw上。

double generate;
int child1, child2, retval, first, second, next, c;
//generate = 10;
first = 1;
second = 1;

retval = pipe (pfd);

if (retval != 0 ) {
    fprintf(stderr, "Pipe failed\n");
    exit(0);
}

printf("Enter the number of Fibinachi numbers you'd like to generate: \n");
scanf("%d", &generate);
//printf("%d\n", generate);

child1 = fork();

if(child1 == 0)
{
    child2 = fork();

    if(child2 == 0)
    {
        printf("Im the child child \n");
        for ( c = 0; c < generate; c++ )
        {
            if ( c <= 1 )
                next = 1;
            else
            {
                next = first + second;
                first = second;
                second = next;
            }
            write (pfd[WRITE_END], &next, sizeof(int));
        }
    }
    else
    {
        printf("Im the child \n");
        FILE * Output;
        Output = fopen("data.txt", "w+");

        for ( c = 0; c < generate; c++ )
        {
            read(pfd[READ_END], &next, sizeof(int));
            fprintf(Output, "%d\n", next);

            printf("%d\n", next);
            wait(NULL);
        }
    }
}
else
{
    printf("Hey, I am the Parent.\n");

}

exit(1);

最佳答案

使用%lf读取双类型变量。
double generate;
scanf("%d", &generate);-->scanf("%lf", &generate);
如果变量的初始化方式类似于generate = 10;,则它将视为generate = 10.0;,并且工作正常。

关于c - 无法识别用户输入,但是如果最初设置了数字,程序将运行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21870920/

10-10 21:26