c++ how to get “one digit exponent” with printf

后端 未结 5 2149
说谎
说谎 2020-12-06 05:48

Is there a way to print in scientific notation less than 3 places for exponent part of number? The 6.1 formatting doesn\'t affect exponent but only the number part:

5条回答
  •  -上瘾入骨i
    2020-12-06 06:16

    I found Zach's answer to be the fastest and simplest method and is also applicable to any OS. I did find that two modifications were needed on the "base =" line for it to work for all numbers. (Otherwise nan's when exponent is negative in cygwin). The extra print statement is just for patran neutral file compatibility. I would have upvoted his answer, but I just started on stackexchange so I don't have sufficient "reputation".

    void PrintScientific(double d)
    {
       int exponent  = (int)floor(log10( fabs(d)));  // This will round down the exponent
       double base      = (d * pow(10.0,  -1*exponent));
    
    if(abs(exponent)<10)
        printf("%13.9lfE%+01d", base, exponent);
    else
        printf("%12.9lfE%+01d", base, exponent);
    }
    

提交回复
热议问题