C语言在运行时在printf中设置十进制数字的计数 [英] Setting count of decimal digits in printf at runtime in C language

查看:37
本文介绍了C语言在运行时在printf中设置十进制数字的计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数字:m,由用户作为参数给出.
例如:

m = 5

m = 7

我在运行时不知道这一点.
然后我计算一个积分并将其保存到一个变量中:answer.
我想用 m 十进制数字打印 answer.
我怎样才能做到这一点?我试过这个:

printf("answer = %(%.mf)d ", answer , m);

这是错误的,我知道,但我该如何解决?

解决方案

如果你有一个带值的变量,请说:

 double val = 3.234003467;

您可以打印到小数点后第二位,例如使用:

printf("This is the value: %0.2f\n", val);

它会输出:3.23

I have a number: m which is given by the user as parameter.
For example:

m = 5 

or

m = 7 

I do not know this at run-time.
I then compute an integral and save it to a variable: answer.
I want to print answer with m decimals digits.
How can I do this? I tried this one:

printf("answer = %(%.mf)d ", answer , m);

It's wrong ,I know ,but how can I solve it?

解决方案

If you have a variable with a value, say:

 double val = 3.234003467;  

You could print out to the 2nd decimal place for example using:

printf("This is the value: %0.2f\n", val);

It would output: 3.23

This page lists several useful formatting specifiers, and how/when to use them.

Here is a complete example of using command line input to create a format string and print out a floating point, with user determined width specifier:

Given the following command line input:
prog.exe 1.123423452345 4
using the following code:

#define TRUE 1
#define FALSE 0
#define bool BOOL

    bool parseDbl(const char *str, double *val);
    bool parseLong(const char *str, long *val);

    int main(int argc, char *argv[])//Use this signature rather than 
    {                               //int main(void) to allow user input
        if(argc != 3) //simple verification that command line contains 2 arguments
        {
            ;   
        }
        double dVal;
        long iVal;
        char format_string[80];
        
        if(parseDbl(argv[1], &dVal));//to simplify code, move the conversions to functions
        if(parseLong(argv[2], &iVal));
        
        //create the format string using inputs from user
        sprintf(format_string, "%s %s%d%s", "User input to \%d decimal Places:  ", "%0.", iVal, "f");
        
        printf(format_string, iVal, dVal);//use format string with user inputs
            
        return 0;
    }
    
bool parseDbl(const char *str, double *val)
{
    char *temp = NULL;
    bool rc = TRUE;
    errno = 0;
    *val = strtod(str, &temp);

    if (temp == str || ((*val == -HUGE_VAL || *val == HUGE_VAL) && errno == ERANGE))
        rc = FALSE;

        return rc;
}
    
bool parseLong(const char *str, long *val)
{
    char *temp;
    bool rc = TRUE;
    errno = 0;
    *val = strtol(str, &temp, 0);

    if (temp == str || errno == ERANGE)
        rc = FALSE;

    return rc;
}
    

The output will be:

这篇关于C语言在运行时在printf中设置十进制数字的计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆