【问题标题】:My function keeps returning 0 instead of the actual value我的函数不断返回 0 而不是实际值
【发布时间】:2021-03-29 21:06:31
【问题描述】:
#include <stdio.h>

int arredonda (double x)
{
    int arredondado;
    if (x - (int)x >= 0.5)
        arredondado = (int)x + 1;
    else
        arredondado = (int)x;
    return arredondado;
}

int main()
{
    double num;
    scanf("%f", &num);
    printf("%d", arredonda(num));
    return 0;
}

这是一个根据小数部分将数字向上或向下舍入的函数。问题是它总是返回 0 和所有值。

【问题讨论】:

标签: c


【解决方案1】:

%lf 必须用于输入double

确保启用编译器的警告!

a.c: In function ‘main’:
a.c:16:13: warning: format ‘%f’ expects argument of type ‘float *’, but argument 2 has type ‘double *’ [-Wformat=]
     scanf("%f", &num);
            ~^   ~~~~
            %lf

我将-Wall -Wextra -pedantic 与 gcc 和 clang 一起使用。


至于舍入本身,有更好的解决方案:round from math.h

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-27
    • 2020-07-25
    • 1970-01-01
    • 2017-10-18
    • 2021-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多