首页 > 解决方案 > 我在方程中输入一个双整数,但一直得到 0

问题描述

我对 C 编程相当陌生,遇到了一个小问题。

我输入 0.05 作为双浮点数,并通过我的解决方案图片中给出的公式运行它以获得答案 0.06242。但是,无论我输入什么内容,我都会得到 0.000000。有人可以向我解释我的代码是否有问题,或者解释我是否在 scanf 和 printf 中都正确使用了“%lf”?谢谢。

解决我的问题

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

main(){
    double guess, pow1,pow2,pow3, estimate;
    printf("Type in an initial guess of the root(for this case type 0.05):  ");
    scanf("%lf", &guess);

    printf("Calculating the root estimate using formula from solution...\n");
    pow1 = pow(guess, 3);
    pow2 = 0.165*pow(guess, 2);
    pow3 = 3*pow(guess, 2);

    estimate = guess - ((pow1 - pow2 + 0.0003993) / (pow3 - 0.33*guess));
    printf("Estimate = %lf\n", estimate);
}

标签: c

解决方案


存在main()而不是int main (void)意味着您正在使用称为 C90 的古老版本的 C,而不是使用标准 C,因为main()只会在古老的 C90 中干净地编译。

C90 不支持%lf除了printf作为编译器扩展之外。它仅支持%f所有浮点类型。这可以解释为什么你会得到奇怪的输出。请参阅printf 中 double 的正确格式说明符

通过获取更新的编译器和更新的 C 学习源来解决这个问题。


推荐阅读