如何在 C++ 中附加一个整数(带整数)

How To Append an Integer (with an Integer) in C++(如何在 C++ 中附加一个整数(带整数))
本文介绍了如何在 C++ 中附加一个整数(带整数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有人可以告诉我如何在 C++ 中附加一个整数(与另一个整数).基本上,如果我有一个值为 67 的 int,我将如何在它后面加上数字 4,所以整数现在是 674?提前致谢!

I was wondering if anyone could tell me how to append an integer (with another integer) in C++. Basically, if I have an int with this the value 67, how would I append it with the number 4 so the integer is now 674? Thanks in advance!

推荐答案

将第一个乘以十的第二个位数的幂,然后将另一个相加.

Multiply first by ten to the power of digit number of second and add the other .

示例:63 和 5

63*10=630
630+5 =635

示例:75 和 34

75*100=7500
7500+34=7534
int i1=75;
int i2=34;
int dn=ceil(log10(i2+0.001));     //0.001 is for exact 10, exact 100, ...
int i3=i1*ceil(pow(10,dn)); <---- because pow would give 99.999999(for some optimization modes)
i3+=i2;

字符串版本需要 2 个 int 到 str 的转换(很慢)和 1 个字符串连接(不快)和 1 个 str 到 int 的转换(很慢).上转换需要 2 次加法、1 次对数、2 次上限、1 次幂、1 次乘法,所有这些都可以在 cpu 中完成,而无需接触主存储器来获取/设置子步骤的数据,这肯定比字符串版本的延迟更小.如果编译器设计将 3-4 个字符串存储在 sse 寄存器中,那么两者都会竞争性能.因为当一个人忙于计算power"函数时,另一个人忙于从 sse 中提取字符串并将其一个一个地放入必要的寄存器并通过开始加法和乘法来构建另一个寄存器.Power(10,x) 函数可以换成 10*10*10.... x 次,所以纯数学版本再次变得更快.

String version needs 2 int to str conversion (which is slow) and 1 string concatenation (which is not fast) and 1 str to int conversion (which is slow). Upper conversion needs 2 additions, 1 logarithm, 2 ceilings, 1 power, 1 multiplication all of which could be done in cpu without touching main memory to get/set data for sub steps that is surely less latency then string versions. If 3-4 character strings are stored in sse registers by compiler design, then both would compete for performance. Because while one would be busy computing "power" function, other would be busy extracting string from sse and putting it necessary registers one by one and constructing on another register by starting additions and multiplications. Power(10,x) function can be traded for 10*10*10.... x times so pure math version becomes faster again.

如果您需要可读性,那么 eq- 的答案是 imo 最好的.

If it is readability you need, eq- 's answer is best imo.

这篇关于如何在 C++ 中附加一个整数(带整数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)