这个C程序我做错了什么?

时间:2012-07-22 05:36:52

标签: c

我有以下代码,我唯一可以看到它评估的是第18行,它是对printf()的调用。它没有进一步发展。

#include <stdio.h>
#include <stdlib.h>

int main (void) {

    int cylNum;
    double disp, pi, stroke, radius;
        pi = 3.14159;

    printf("Welcome to the Engine Displacement Calculator!\n");

    cylNum = scanf("Enter number of cylinders (then press enter): \n");

    stroke = scanf("Enter stroke: \n");

    radius = scanf("Enter radius: \n");

    disp = radius * radius * pi * stroke * cylNum;

    printf("Displacement is: %f", disp);

    getchar();
    printf("Press any key to exit!");
    return 0;
}

4 个答案:

答案 0 :(得分:2)

您尝试读取的变量应该是“scanf()”的参数,而不是scanf()的结果:

printf("Enter number of cylinders (then press enter): ");
scanf("%d", &cylNum);
...

答案 1 :(得分:1)

scanf函数是读取值。

所以行

cylNum = scanf("Enter number of cylinders (then press enter): \n"); 

应该是以下几行

printf("Enter number of cylinders (then press enter): \n");
scanf("%d", &cylNum);

您需要检查scanf的返回值,以确保它为1,即已进行转换。

所以代码应该是

do {
   printf("Enter number of cylinders (then press enter): \n");
} while (scanf("%d", &cylNum) != 1);

对于变量disp, pi, stroke, radius,您需要在"%lf"函数中使用scanf而不是"%d

请参阅scanfprintf

答案 2 :(得分:0)

“scanf”不会像您尝试的那样采用参数。

printf("Enter number of cylinders (then press enter): \n");
scanf(" %d", &cylNum);

printf("Enter stroke: \n");
scanf(" %lf", &stroke);

答案 3 :(得分:0)

#include <stdio.h>
#include <stdlib.h>
int main (void) {

    int cylNum;
    float disp, pi, stroke, radius;
    pi = 3.14159;
    printf("Welcome to the Engine Displacement Calculator!\n\n");
    printf("Enter number of cylinders (then press enter): ");
    scanf("%d", &cylNum);
    printf("Enter stroke: ");
    scanf("%f", &stroke);
    printf("Enter radius: ");
    scanf("%f", &radius);
    disp = radius * radius * pi * stroke * cylNum;
    printf("Displacement is: %f\n\n", disp);
    return 0;
}