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

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

相关推荐
Wang's Blog5 小时前
Go-Zero项目开发4: 用户服务搜索、详情与统一错误处理
开发语言·golang
我星期八休息5 小时前
网络编程—应用层HTTP协议
linux·运维·开发语言·前端·网络·网络协议·http
梅雅达编程笔记5 小时前
零基础学 Python 第14章 | 模块、包与第三方库
开发语言·python·django·numpy·pandas
Mr__Miss6 小时前
Java泛型完全指南:从入门到精通
java·开发语言·python
赵庆明老师6 小时前
Vben精讲:14-Vben远程加载语言包
开发语言·vben
jinyishu_7 小时前
模拟实现 C++ 栈和队列——从适配器模式看懂 STL 容器之美
java·c++·适配器模式
hehelm7 小时前
AI大模型接入SDK—通用模块设计
linux·开发语言·c++
梅雅达编程笔记8 小时前
零基础学 Python 第15章 | 类与对象:面向对象编程入门
开发语言·python·django·numpy·pandas
行思理8 小时前
微信支付“商家转账用户确认模式”,新手教程
java·开发语言·微信
麻瓜老宋9 小时前
AI开发C语言应用按步走,表达式计算器calc的第一步,中缀表达式词法分析
c语言·开发语言·atomcode