如何通过自己的功能将浮动绕上和向上c 上下


double round(double a)
{
    double b, c, f, g;
    float d[2];
    c = modf(a, &b);
    if (a > 0) {
        f = a - c;
        g = a - c + 1;
        d[0] = f;
        d[1] = g;
        return d[0], d[1];
    }
    else {
        f = a - c;
        g = a - c - 1;
        d[0] = f;
        d[1] = g;
        return d[0], d[1];
    }
}

我需要获得2个数字的结尾(对于ex:如果我有num 12.34,我想获得12和13)这是我为pos和neg数字舍入的功能。但是它仅返回1个值((所以我堆栈...请帮助如何返回2个值?

您无法在返回中返回两件事,因此return d[0],d[1]编译但无法正常工作。您可以在功能原型中使用两个参考参数返回。像void round(double a, double* result1, double* result2)一样。在功能中,将d[0]设置为*result1,将d[1]设置为*result2

另一件事:您确定a时线g = a - c - 1;是正确的吗?我认为您需要进行g = a + c - 1;,因为A是负数。

#include "pch.h"
#include <iostream>
#include <array>
using namespace std;
auto rounding(double x)
{
    int part = static_cast<int>(x);
    if (x < 0.0)
    {
        return array<int, 2> {
            part - 1, part
        };
    }
    else
    {
        return array<int, 2> {
            part, part + 1
        };
    }
}
int main()
{
    double x;
    cout << "Please, enter a float number to round: ";
    cin >> x;
    auto r1 = rounding(x);
    if (x > 0) {
        cout << "A lower value: " << r1[0] << endl << "A bigger value: " << r1[1];
    }
    else {
        cout << "A bigger value: " << r1[0] << endl << "A lower value: " << r1[1];
    }
}

相关内容

最新更新