【自动驾驶解决方案】C++取整与保留小数位

一、C++基础

1.1double型保留小数为,并以字符输出

cpp 复制代码
#include <iostream>
#include <sstream>
#include <iomanip> // 包含std::fixed

int main() {
	//浮点数
    double number = 3.1415926;
	//转换工具类stream
    std::stringstream stream;
    stream << std::fixed << std::setprecision(2) << number;
    //c++11内置函数str()
    std::string result = stream.str();
    //输出
    std::cout << result << std::endl;
    return 0;
}

1.2 四舍五入

常用的方法是使用std::ostringstream和std::fixed结合使用std::setprecision和std::round来实现

cpp 复制代码
#include <iostream>
#include <sstream>
#include <iomanip> // 包含std::fixed
#include <cmath> // 包含std::round

int main() {
    double number = 3.1415926;
    
    std::ostringstream stream;
    stream << std::fixed << std::setprecision(2) << std::round(number * 100) / 100;
    
    std::string result = stream.str();
    
    std::cout << result << std::endl;
    
    return 0;
}

二 自动驾驶方案

1.1 目标跟踪部分代码

cpp 复制代码
	.
	.
	.
	.
	//获取目标距离
    double distance = cvt_point(cv::Point(center_x, center_y));
    std::stringstream stream;
    stream << std::fixed << std::setprecision(2) << distance;
    //转为有2位小数的字符
    std::string disttance_str = stream.str();

    // 通过opencv可视化
    cv::putText(
      image, 
      //cv::format("ID: %s", uuid_str.c_str()),
      cv::format("Dis: %s m", disttance_str.c_str()),
      cv::Point(left, top - 5),
      cv::FONT_HERSHEY_SIMPLEX,
      3,  // font scale
      color,
      10,  // thickness /home/nvidia/yolo_test/src/track
      cv::LINE_AA);
  }
  .
  .
  .
  

代码效果图,小数点只保留两位

相关推荐
先知后行。5 分钟前
C/C++八股文
java·开发语言
程序员buddha40 分钟前
C语言数组详解
c语言·开发语言·算法
寻找华年的锦瑟40 分钟前
Qt-视频播放器
开发语言·qt
又是忙碌的一天1 小时前
Java IO流
java·开发语言
fish_study_csdn1 小时前
Python内存管理机制
开发语言·python·c python
卡提西亚3 小时前
C++笔记-25-函数模板
c++·笔记·算法
ghie90903 小时前
MATLAB/Simulink水箱水位控制系统实现
开发语言·算法·matlab
cs麦子3 小时前
C语言--详解--指针--上
c语言·开发语言
像风一样自由20203 小时前
Go语言入门指南-从零开始的奇妙之旅
开发语言·后端·golang
R&L_201810014 小时前
C++之内联变量(Inline Variables)
c++·c++新特性