问题
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