【自动驾驶解决方案】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);
  }
  .
  .
  .
  

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

相关推荐
无限的鲜花6 小时前
反射(原创推荐)
java·开发语言
yongche_shi6 小时前
ragas官方文档中文版(五十)
开发语言·python·ai·ragas·如何评估和改进 rag 应用
一路向北he6 小时前
字节钢铁军团--“提供情境,而非控制”
java·开发语言·前端
QiLinkOS6 小时前
第三视觉理解徐玉生与他的商业活动(30)
大数据·c++·人工智能·算法·开源协议
mit6.8246 小时前
阅读的核心,是再读
c++
AI行业学习7 小时前
Notepad++ 官方下载 + 完整安装 + 全套优化配置(2026最新)
开发语言·人工智能·python·前端框架·html·notepad++
大圣编程8 小时前
Python中continue语句的用法是什么?
开发语言·前端·python
upgrador9 小时前
基础知识:C++ STL构造函数的左闭右开惯例及其实现原理
开发语言·c++
yoothey9 小时前
报废审批流规则引擎设计——责任链模式完整实现
linux·开发语言·bash
geovindu10 小时前
python: Functional Options Pattern
开发语言·后端·python·设计模式·惯用法模式·函数式选项模式