描述
写出一个程序,接受一个正浮点数值,输出该数值的近似整数值。如果小数点后数值大于等于 0.5 ,向上取整;小于 0.5 ,则向下取整。
数据范围:保证输入的数字在 32 位浮点数范围内
输入描述:
输入一个正浮点数值
输出描述:
输出该数值的近似整数值
示例1
输入:5.5
输出:6
说明:0.5>=0.5,所以5.5需要向上取整为6
示例2
输入:2.499
输出:2
说明:
0.499<0.5,2.499向下取整为2
思路
1.这道题的关键是将浮点数的整数部分和小数部分提取出来
代码
FloatCoverter.h
#pragma once
#include <mutex>
class FloatCoverter
{
public:
static FloatCoverter* getInstance();
public:
void float2Int();
private:
FloatCoverter() = default;
~FloatCoverter() = default;
private:
static FloatCoverter* instance;
static std::mutex iMutex;
};
FloatCoverter.cpp
#include <iostream>
#include <cmath>
#include "FloatCoverter.h"
FloatCoverter* FloatCoverter::instance = nullptr;
std::mutex FloatCoverter::iMutex;
FloatCoverter* FloatCoverter::getInstance()
{
std::unique_lock<std::mutex> lock(iMutex);
if (nullptr == instance) {
instance = new FloatCoverter();
}
return instance;
}
void FloatCoverter::float2Int()
{
/* input float data */
float_t number = 0.0;
std::cin >> number;
/* verify validity */
if (number <= float_t(0)) {
std::cout << "A number less than or equal to float(0)" << std::endl;
return;
}
/* extract integer part and float part of float number */
int32_t intVal = number;
float_t floatVal = number - float_t(intVal);
if (floatVal >= float_t(0.5)) {
intVal += 1;
}
std::cout << intVal << std::endl;
}
main.cpp
#include "FloatCoverter.h"
int main(int argc, char** argv)
{
auto floatCoverter = FloatCoverter::getInstance();
floatCoverter->float2Int();
return 0;
}
测试
测试环境
visual studio 2019
测试结果
输入:1.22
输出:1
输入:1.501
输出:2
输入:0
输出:"A number less than or equal to float(0)"