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

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

相关推荐
“AI国潮设计-小江”6 分钟前
【AIGC实战】Python+SDXL打造“潮汕英歌舞IP”万能立牌插件,批量生成“发财元宝蛋糕”视觉营销方案(附源码)
开发语言·人工智能·python·prompt·aigc
lhbweilai38 分钟前
分析FreeRTOS内核对象API的源码实现(八)
c语言·开发语言·stm32·单片机
努力努力再努力wz42 分钟前
【C++高阶系列】C++20 协程底层原理:函数为什么能暂停?从状态机到 Task,彻底串起挂起、恢复与协程调度
开发语言·c++·c++20·1024程序员节
咩咩啃树皮1 小时前
JavaScript 中 this 指向为什么总在变?
开发语言·前端·javascript
程序员清风1 小时前
算法题中的边界条件、测试与调试
开发语言·算法·kotlin
划破黑暗的第一缕曙光1 小时前
[C++]:4.模板
c++·template·模板·函数模版·类模版
砚底藏山河1 小时前
python量化实操:冷热分层存储
java·开发语言·python·金融
十五年专注C++开发1 小时前
pybind11:一个跨C++和Python平台的编程库
开发语言·c++·python·pybind11
CodeYp20191 小时前
第11讲:stack 和 queue
开发语言·c++·queue·stack
咩咩啃树皮2 小时前
JavaScript 异步流程为什么容易失控?从回调到可维护设计
开发语言·javascript·ecmascript