# 如何将结果输出到用户先前输入的小数点数 (C)？

[英]How do I output a result to the number of decimal-points user previously entered (C)?

I'm trying to output my results to the decimal accuracy the user has input.我试图将我的结果输出到用户输入的十进制精度。 In other words, if they enter 145, then it outputs to 0 dp - if they enter 145.67, it outputs the result to 2 dp换句话说，如果输入 145，则输出为 0 dp - 如果输入 145.67，则输出结果为 2 dp

I've tried achieving this by trying different things with `%.lf` but didn't manage to do it so far.我已经尝试通过使用`%.lf`尝试不同的东西来实现这一点，但`%.lf`还没有做到。 Is there a way to do this in C?有没有办法在 C 中做到这一点？ If so, is there a name for it - so I can learn more about it.如果是这样，是否有它的名称 - 以便我可以了解更多信息。

``````#include <math.h>
#include <stdio.h>

int main() {
// Using long, double or something else?
double number, fourthRoot;

printf("Enter a number: ");
scanf("%lf", &number);

fourthRoot = sqrt(sqrt(number));

printf("4th root of number %lf is %.10lf", number, fourthRoot);

return 0;
}
``````

Read user input as a line with `fgets()` or some `scanf("%s",...` -like code.使用`fgets()`或一些`scanf("%s",...`类的代码将用户输入读取为一行

``````char buf[400];
if (fgets(buf, sizeof buf, stdin)) {
``````

And then process the string.然后处理字符串。 One way is with `sscanf()`一种方法是使用`sscanf()`

``````  int n;
// Get the number and offset to end of scan
if (sscanf(buf, "%lf%n", &number, &n) == 1) {
// Look for '.'
char *dp = strchr(buf, '.');
if (dp && dp < buf + n) {
// decimal point found
int pre = buf + n - dp - 1;
printf("%.*f\n", pre, number);
``````

This works OK but does get fooled if exponential notation used.这工作正常，但如果使用指数表示法会被愚弄。 Additional code could look for the `E` or `e` (or `P` , `p` with hexadecimal FP notation).附加代码可以查找`E``e` （或`P``p`与十六进制 FP 表示法）。

There are a lot of edge cases that you should worry about, but this should get you started:您应该担心很多边缘情况，但这应该会让您开始：

``````#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static int
compute_root(const char *s)
{
char *end;
double number = strtod(s, &end);
if( *end ){
fprintf(stderr, "Invalid input: %s\n", s);
return 1;
}
char *dp = strchr(s, '.');
int precision = dp ? end - dp - 1: 0;
char fmt[256];
snprintf(fmt, sizeof fmt, "4th root of %%s is %%.%dlf\n", precision);
printf(fmt, s, pow(number, .25));
return 0;
}

int
main(int argc, char **argv)
{
int errors = 0;
char buf[64];
if( argc > 1 ){
while( *++argv ){
errors += compute_root(*argv);
}
} else while( scanf("%63s", buf) == 1 ){
errors += compute_root(buf);
}
return errors ? EXIT_FAILURE : EXIT_SUCCESS;
}
``````

As an exercise, consider inputs like `5.345e4` .作为练习，考虑像`5.345e4`这样的输入。 The above code will output with a precision of 5, but you probably want 3. Handling those cases is non-trivial (for certain definitions of "trivial").上面的代码将以 5 的精度输出，但您可能需要 3。处理这些情况并非易事（对于“微不足道”的某些定义）。