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

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

相关推荐
a程序小傲11 分钟前
阿里Java面试被问:.Java 8中Stream API的常用操作和性能考量
开发语言·windows·python
酷酷的佳15 分钟前
C语言--数组作为函数参数
c++
爱装代码的小瓶子34 分钟前
【c++进阶】从C++98到C++11的奇妙旅程(故事科普版)
开发语言·c++
智航GIS37 分钟前
2.3 运算符详解
开发语言·python
web3.088899941 分钟前
接入API-自动化批量获取淘宝商品详情数据
开发语言·python
世转神风-1 小时前
qt-在字符串中指定位置插入字符串
开发语言·qt
时光呀时光慢慢走1 小时前
C# WinForms 实战:MQTTS 客户端开发(与 STM32 设备通信)
开发语言·c#
superman超哥1 小时前
仓颉类型别名的使用方法深度解析
c语言·开发语言·c++·python·仓颉
LFly_ice1 小时前
Next-4-路由导航
开发语言·前端·javascript
3824278272 小时前
python :__call__方法
开发语言·python