首页 > 解决方案 > 如何在 C++ 中使用数学

问题描述

当我将 na 值设为 1 时,为什么结果等于 2 而不是 3。这是我的代码

#include <stdio.h>

int main()
{
    int n;
    float result;

    scanf("%d", &n);
    result = 1 + n/(2*n+1)*3/2;
    while (n != 1)
    {
        result = result*(n-1)/(2*(n-1)+1);
        n = n-1;
    }
    result = result * 2;
    printf("%f", result);
    return 0;
}

标签: c++math

解决方案


因为nint,所以右侧的数学是整数数学,而不是浮点数。然后将结果提升为浮动存储到result.

result = 1 + n/(2*n+1)*3/2;
result = 1 + 1/3*3/2;
result = 1 + 1;
result = float(2);

使用float常量使其实际计算为浮点数。

result =1.0f + n/(2.0f*n+1.0f)*3.0f/2.0f;

推荐阅读