Setting count of decimal digits in printf at runtime in C language

有些话、适合烂在心里 提交于 2020-08-10 23:11:59

问题


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?


回答1:


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:



来源:https://stackoverflow.com/questions/61920616/setting-count-of-decimal-digits-in-printf-at-runtime-in-c-language

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!