如何通过自己的功能将浮动绕上和向上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个数字的结尾(对于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];
}
}
相关文章:
- 没有为自己的结构调用列表推回方法
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- 在c++中为我自己的基于指针的数组分配内存的正确方法
- C++从对象自己的类中删除对象
- 使用 std::optional,而不是自己的结构
- 检查一个类型是否直接派生自"enable if"上下文中的另一个类型(是其子类型)
- 子轴围绕父轴而不是他自己的轴旋转
- 这个C++编译器优化(在自身的实例上调用对象自己的构造函数)的名称是什么,它是如何工作的?
- 使用 'typename' 关键字将非类型视为依赖上下文中的类型
- C++ 如何为自己的迭代器类从迭代器转换为const_iterator?
- 重载 + 自己的类和 std::string 的运算符
- 类无法访问自己的私有静态 constexpr 方法 - Clang bug?
- 是否可以在不填充自己的参数的情况下将模板函数作为参数传递?
- 如何访问模板参数自己的模板参数?
- 将矩阵乘以我自己的输入的向量
- 您应该在什么时候创建自己的异常类型
- 派生类是从基类继承 v 指针并仅使用它,还是也有自己的 v 指针?
- string1 == string2 和你自己的 for 循环比较有什么区别?
- 如何正确包含我自己的标头?
- 如何通过自己的功能将浮动绕上和向上c 上下