简体   繁体   中英

how to use math in c++

When I give my na value of 1 why does the result equal to 2 and not 3. Here is my code

#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;
}

Since n is an int , the math on the right side is done as integer math, not float. Then the results is promoted to float to store into result .

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

Use float constants to get it to actually calculate as a float.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM