有什么方法可以绕字符串
Is there any way to round a string?
所以我有一个exampe "-389761456.6570000000"
的字符串,我需要将此数字舍入dor后面的4个字符。我为此写了一个整体功能,但它太长(100行)。我不能这样转换:
void Calculator::Display(string a)
{
long double q = stod(a);
cout << setprecision(4) << q << endl;
}
因为它看起来像这样(3.89e^-10等)(只是一个示例,而不是真正的结果)我想要像这个"-389761456.6570"
这样的smth有什么方法可以做吗?
当然,它仅需要几行代码;当然不是100。只需考虑四舍五入的规则:要舍入到4位数字,请查看第五位数;如果大于'5'
,则将其添加到第四位;如果小于'5'
,请独自留下第四位。如果完全是'5'
,则第四位之后的任何内容不是零,请在第四位添加一个;否则,请应用您的抢七规则(往返,往返,圆形,朝零等)。当您将一个添加到第四位时,它可能会从'9'
滚动到大于'9'
的东西;如果发生这种情况,请将一个添加到第三位,等等。完成所有完成后,在第四位之后丢弃字符。
这应该做您想要的。但是,只使用系统库来完成此操作要容易得多。
#include <iostream>
#include <string>
void increment( std::string& num )
{
for ( auto ch = num.rbegin(); ch != num.rend(); ch++ )
{
switch ( *ch )
{
case '9':
*ch = '0';
case '.':
continue;
case '-':
num.insert( 1, 1, '1' );
return;
default:
(*ch)++;
return;
}
}
num.insert( 0, 1, '1' );
}
std::string round( const std::string& num, size_t precision )
{
size_t dot = num.find( '.' );
if ( dot == std::string::npos || dot + precision >= num.size() )
{
return num;
}
size_t length = std::min( dot + precision + 1, num.size() );
char lastCh = num[ length ];
std::string result = num.substr( 0, length );
if ( lastCh >= '5' && lastCh <= '9' )
{
increment( result );
}
return result;
}
int main()
{
std::cout << round( "123.45", 4 ) << "n";
std::cout << round( "123.456", 4 ) << "n";
std::cout << round( "123.4567", 4 ) << "n";
std::cout << round( "123.45678", 4 ) << "n";
std::cout << round( "123.456789", 4 ) << "n";
std::cout << round( "123.456723", 4 ) << "n";
std::cout << round( "999.9999995", 4 ) << "n";
std::cout << round( "-123.456723", 4 ) << "n";
std::cout << round( "-999.9999995", 4 ) << "n";
}
相关文章:
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- 当我尝试添加 2 个大字符串时,我无法弄清楚出了什么问题
- 初始化或分配空字符串文字到指向 C 中的 char 的指针或指向 C++ 中 const char 的指针的原因是什么
- 在C++17中,引用const字符串的语义应该是什么
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 字符串上的 C++ push_back() 和 pop_back() 的 Kotlin 是什么?
- 我的逻辑反转字符串中的元音有什么问题?
- 我还可以添加什么来按空格或空格正确拆分C++字符串?
- 这里的字符串函数是什么意思
- 我正在尝试使用 while 循环从字符串中删除字母,直到没有字母。我在这里做错了什么?
- 字符串::格式有什么用. 我也没有在互联网上得到它
- 从 argv[1] 转换为字符 * 字符串后有什么问题?
- 如果结构中的字符串比使用的 p/调用签名长或短,会发生什么情况?
- 这两个C++语句连接字符串有什么区别?
- "in-situ without memory allocation" 字符串的愚蠢实现意味着什么?
- 我做错了什么?反向字符串 C++
- 将位字符串转储到二进制文件的最佳方法是什么
- 使用 CStringW/CStringA 和 CT2W/CT2A 转换字符串有什么区别?
- 使用 const char* 初始化 const ref 字符串成员时幕后会发生什么
- 仅威胁唯一字符串 - 什么是更快的 vector<std::string> 或只是 std::string