C语言实例:输出浮点数和双精度浮点数的四种函数

C语言中有多种函数可以用来输出浮点数,常见的有printf()、puts()、putchar()、fputs()等。下面是具体的实例:

在C语言中,%f是用来格式化输出浮点数的占位符。例如,printf(“浮点数为:%f\n”, num); 中的%f表示输出变量num的值并按照浮点数格式进行显示。

1. printf函数

#include <stdio.h>

int main()
{
    float num = 3.14159;
    printf("浮点数为:%f\\n", num);
    return 0;
}

输出结果:

浮点数为:3.141590

2. puts函数

#include <stdio.h>

int main()
{
    float num = 3.14159;
    char str[20];
    sprintf(str, "%f", num);
    puts(str);
    return 0;
}

输出结果:

3.141590

3. putchar函数

#include <stdio.h>

int main()
{
    float num = 3.14159;
    char str[20];
    sprintf(str, "%f", num);
    int i = 0;
    while(str[i] != '\\0')
    {
        putchar(str[i]);
        i++;
    }
    putchar('\\n');
    return 0;
}

输出结果:

3.141590

4. fputs函数

#include <stdio.h>

int main()
{
    float num = 3.14159;
    char str[20];
    sprintf(str, "%f", num);
    fputs(str, stdout);
    return 0;
}

输出结果:

3.141590

C语言中输出双精度浮点数的函数和输出单精度浮点数的函数一样,常见的有printf()、puts()、putchar()、fputs()等。下面是具体实例:

在C语言中,%lf是用来格式化输出双精度浮点数的占位符。例如,printf(“双精度浮点数为:%lf\n”, num); 中的%lf表示输出变量num的值并按照双精度浮点数格式进行显示。

1. printf函数

#include <stdio.h>

int main()
{
    double num = 3.1415926535;
    printf("双精度浮点数为:%lf\\n", num);
    return 0;
}

输出结果:

双精度浮点数为:3.141593

2. puts函数

#include <stdio.h>

int main()
{
    double num = 3.1415926535;
    char str[20];
    sprintf(str, "%lf", num);
    puts(str);
    return 0;
}

输出结果:

3.141593

3. putchar函数

#include <stdio.h>

int main()
{
    double num = 3.1415926535;
    char str[20];
    sprintf(str, "%lf", num);
    int i = 0;
    while(str[i] != '\\0')
    {
        putchar(str[i]);
        i++;
    }
    putchar('\\n');
    return 0;
}

输出结果:

3.141593

4. fputs函数

#include <stdio.h>

int main()
{
    double num = 3.1415926535;
    char str[20];
    sprintf(str, "%lf", num);
    fputs(str, stdout);
    return 0;
}

输出结果:

3.141593

猜你喜欢

转载自blog.csdn.net/weixin_51624736/article/details/129634101