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

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

相关推荐
2501_941802482 分钟前
面向微服务限流、熔断与降级协同的互联网系统高可用架构与多语言工程实践分享
开发语言·python
2501_941875288 分钟前
分布式系统中的安全权限与审计工程实践方法论经验总结与多语言示例解析分享
开发语言·rabbitmq
无限进步_15 分钟前
【C语言】堆排序:从堆构建到高效排序的完整解析
c语言·开发语言·数据结构·c++·后端·算法·visual studio
雾岛听蓝20 分钟前
STL 容器适配器:stack、queue 与 priority_queue
开发语言·c++
CSDN_RTKLIB22 分钟前
【One Definition Rule】多编译单元定义同名全局变量
开发语言·c++
lang2015092841 分钟前
AQS共享锁的传播机制精髓
java·开发语言
云栖梦泽1 小时前
变量与数据类型:从“默认不可变”说起
开发语言
趁月色小酌***1 小时前
Java知识点概要2
java·开发语言
superman超哥1 小时前
Rust 可变借用的独占性要求:排他访问的编译期保证
开发语言·后端·rust·rust可变借用·独占性要求·排他访问·编译期保证
fengfuyao9851 小时前
基于C#实现的支持五笔和拼音输入的输入法
开发语言·c#