草庐IT

c++ - 限制固定输出的尾随零数

coder 2024-02-05 原文

我需要一些有关使用 C++ 流进行输出格式化的帮助。我想打印带有固定小数点且最多 2 个尾随位置的数字。我尝试了以下方法:

#include <iostream>
#include <iomanip>
using namespace std;

int main(int argc, char **argv)
{
  float testme[] = { 0.12345, 1.2345, 12.345, 123.45, 1234.5, 12345 };

  std::cout << std::setprecision(2) << std::fixed;

  for(int i = 0; i < 6; ++i)
  {
      std::cout << testme[i] << std::endl;
  }

  return 0;
}

输出是:

0.12
1.23
12.35
123.45
1234.50
12345.00

但我想拥有

0.12
1.23
12.35
123.45
1234.5
12345

我能否在不使用额外的字符串操作的情况下实现这一点?

最佳答案

我不知道适合的操纵器,因此您可以使用:

#include <iostream>
#include <iomanip>
#include <cmath>

template <typename T>
struct Fixed
{
    const T& value;
    const unsigned precision;
    const T significant;

    Fixed(const T& value, unsigned precision)
    : value(value), precision(precision), significant(std::pow(10, precision))
    {}

    void write(std::ostream& stream) const {
        // Adjust stream settings
        std::ostream::char_type restore_fill = stream.fill('0');
        std::ios_base::fmtflags restore_flags = stream.setf(
            std::ios_base::fixed, std::ios_base::floatfield);
        std::streamsize restore_precision = stream.precision(0);

        // Split the floating point into an integral and rounded fractional part
        T integral;
        unsigned long fractional = std::round(significant * std::modf(value, &integral));

        // Determine the length of the fractional part
        unsigned digits = precision;
        while(fractional && fractional % 10 == 0) {
            fractional /= 10;
            --digits;
        }

        // Carry over to the integral part
        if( ! digits && fractional) {
            integral += 1;
            fractional = 0;
        }

        // Output
        stream << integral;
        if(fractional) {
            stream <<  '.' << std::setw(digits) << fractional;
        }

        // Restore stream settings
        stream.precision(restore_precision);
        stream.flags(restore_flags);
        stream.fill(restore_fill);
    }
};

template <typename T>
inline Fixed<T> fixed(const T& value, unsigned precision) {
    return Fixed<T>(value, precision);
}

template <typename T>
inline std::ostream& operator << (std::ostream& stream, const Fixed<T>& value) {
    value.write(stream);
    return stream;
}

int main(int argc, char **argv)
{
  float testme[] = { 0.12345, 1.2345, 12.345, 123.45, 1234.5, 12345 };
  for(int i = 0; i < 6; ++i)
  {
      std::cout << fixed(testme[i], 2) << std::endl;
  }

  return 0;
}

关于c++ - 限制固定输出的尾随零数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27202103/

有关c++ - 限制固定输出的尾随零数的更多相关文章

  1. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  2. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  3. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

  4. ruby - 如何进行排列以有效地定制输出 - 2

    这是一道面试题,我没有答对,但还是很好奇怎么解。你有N个人的大家庭,分别是1,2,3,...,N岁。你想给你的大家庭拍张照片。所有的家庭成员都排成一排。“我是家里的friend,建议家庭成员安排如下:”1岁的家庭成员坐在这一排的最左边。每两个坐在一起的家庭成员的年龄相差不得超过2岁。输入:整数N,1≤N≤55。输出:摄影师可以拍摄的照片数量。示例->输入:4,输出:4符合条件的数组:[1,2,3,4][1,2,4,3][1,3,2,4][1,3,4,2]另一个例子:输入:5输出:6符合条件的数组:[1,2,3,4,5][1,2,3,5,4][1,2,4,3,5][1,2,4,5,3][

  5. ruby - 将 spawn() 的标准输出/标准错误重定向到 Ruby 中的字符串 - 2

    我想使用spawn(针对多个并发子进程)在Ruby中执行一个外部进程,并将标准输出或标准错误收集到一个字符串中,其方式类似于使用Python的子进程Popen.communicate()可以完成的操作。我尝试将:out/:err重定向到一个新的StringIO对象,但这会生成一个ArgumentError,并且临时重新定义$stdxxx会混淆子进程的输出。 最佳答案 如果你不喜欢popen,这是我的方法:r,w=IO.pipepid=Process.spawn(command,:out=>w,:err=>[:child,:out])

  6. ruby - 使用 `+=` 和 `send` 方法 - 2

    如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:

  7. ruby - Ruby 是否使用 $stdout 来写入 puts 和 return 的输出? - 2

    我想知道Ruby用来在命令行打印这些东西的输出流:irb(main):001:0>a="test"=>"test"irb(main):002:0>putsatest=>nilirb(main):003:0>a=>"test"$stdout是否用于irb(main):002:0>和irb(main):003:0>?而且,在这两次调用之间,$stdout的值是否有任何变化?另外,有人能告诉我打印/写入这些内容的Ruby源代码吗? 最佳答案 是的。而且很容易向自己测试/证明。在命令行试试这个:ruby-e'puts"foo"'>test.

  8. ruby-on-rails - 无法在 Rails 助手中捕获 block 的输出 - 2

    我在使用自定义RailsFormBuilder时遇到了问题,从昨天晚上开始我就发疯了。基本上我想对我的构建器方法之一有一个可选block,以便我可以在我的主要content_tag中显示其他内容。:defform_field(method,&block)content_tag(:div,class:'field')doconcatlabel(method,"Label#{method}")concattext_field(method)capture(&block)ifblock_given?endend当我在我的一个Slim模板中调用该方法时,如下所示:=f.form_field:e

  9. ruby - 如何计算 Liquid 中的变量 +1 - 2

    我对如何计算通过{%assignvar=0%}赋值的变量加一完全感到困惑。这应该是最简单的任务。到目前为止,这是我尝试过的:{%assignamount=0%}{%forvariantinproduct.variants%}{%assignamount=amount+1%}{%endfor%}Amount:{{amount}}结果总是0。也许我忽略了一些明显的东西。也许有更好的方法。我想要存档的只是获取运行的迭代次数。 最佳答案 因为{{incrementamount}}将输出您的变量值并且不会影响{%assign%}定义的变量,我

  10. ruby - 在 Ruby 中将整数格式化为固定长度的字符串 - 2

    有没有一种简单的方法可以将给定的整数格式化为具有固定长度和前导零的字符串?#convertnumberstostringsoffixedlength3[1,12,123,1234].map{|e|???}=>["001","012","123","234"]我找到了解决方案,但也许还有更聪明的方法。format('%03d',e)[-3..-1] 最佳答案 如何使用%1000而不是进行字符串操作来获取最后三位数字?[1,12,123,1234].map{|e|format('%03d',e%1000)}更新:根据theTinMan的

随机推荐