To output to n decimal places of circumference

Asked 2 years ago, Updated 2 years ago, 157 views

Hi, everyone. Input: n is entered within 25 and output: output: from below the decimal point of the circumference to n digits.

#include <stdio.h>
int main() {
    int n;
    char py[30] = "3.14159265358979323846264";
    scanf("%d", &n);
    n + = 2; //"3." Add 2 to n because this part is 2 characters long.
    for (int i = 0; i < n; i++) {
        printf("%c", py[i]);
    }
    return 0;
}

There are many other ways to print it out by replacing it with a string, such as the above code. But the way I thought about printing it out in real numbers is

#include <stdio.h>
int main() {
    int n;
    double py = 3.14159265358979323846264;
    scanf("%d", &n);
    printf("%.%df", n, py);
    return 0;
}

It's something like this. Of course, it failed and %df was printed (%.% in a row) and "%" escaped. "." is not printed.) The output up to the decimal point can be an integer, but is it too much for a variable? Or should I cut it before I print it out? I'm sorry to bother you with this question.

c float

2022-09-20 16:55

2 Answers

#include <stdio.h>

int main()
{

    double pi = 3.14159265358979323846264;
    int i;

    for (i = 0; i < 15; i++)
        printf("%.*lf\n", i, pi);

    return 0;
}
3
3.1
3.14
3.142
3.1416
3.14159
3.141593
3.1415927
3.14159265
3.141592654
3.1415926536
3.14159265359
3.141592653590
3.1415926535898
3.14159265358979

https://docs.microsoft.com/en-us/cpp/c-runtime-library/format-specification-syntax-printf-and-wprintf-functions?view=msvc-160#precision-specification

If the precision specification is an asterisk (*), an int argument from the argument list supplies the value. In the argument list, the precision argument must precede the value that's being formatted, as shown in this example:

printf( "%.*f", 3, 3.14159265 ); /* 3.142 output */


2022-09-20 16:55

The first argument of the printf function can be in the form of a string. You can put a " type of string directly, but you can also use a string stored in the array. So you can do what you want to do if you create a string in advance with the printf function and then put that string in the printf function.

See the

code.

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>

int main()
{
    double py = 3.14159265358979323846264;
    char format_str[20] = { 0, };

    int n;
    scanf("%d", &n);

    sprintf(format_str, "%%.%df", n);

    printf(format_str, py);

    return 0;
}

.


2022-09-20 16:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.