如何使用自己的函数将 float 舍入为上下值 c++?

How to round float to up and down value c++ with own function?

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 个数字(例如:如果我有 num 12.34,我想得到 12 和 13)这是我对 pos 和 neg 数字进行舍入的函数。但它 return 只有 1 个值((所以我正在堆栈...请帮助如何 return 2 个值?

你不能 return return 中的两个东西,所以 return d[0],d[1] 可以编译,但不能像你预期的那样工作。你可以在函数原型中使用两个引用参数来return。类似于 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];
    }
}