如何显示浮点数



这是我的C++代码。

#include <iostream>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
int main()
{
    FILE *f1;
    char c;
    int num[100], tokenvalue = 0, i = 0, j = 0;
    f1 = fopen("test.txt", "r");
    while ((c = getc(f1)) != EOF)
    {
        if (isdigit(c))
        {
            tokenvalue = c - '0';
            c = getc(f1);
            while (isdigit(c))
            {
                tokenvalue = tokenvalue * 10 + (c - '0');
                c = getc(f1);
            }
            num[i++] = tokenvalue;
            ungetc(c, f1);
        }
    }
    printf("nThe no's in the program aren");
    for (j = 0; j < i; j++)
    {
        printf("%d", num[j]);
        printf("n");
    }
    int z;
    scanf("%d", &z);
    return 0;
}

我的test.txt输入文件有:

Name: Md. Jakir Hossin
Age: 23
Name: Shafi Mahmud
Age: 18.5
Name: Asmaul Husna
Age: 28
Name: Md. Jahirul Haque
Age: 30.4

输出:

[输出][1]

这个程序显示任何int数,但不显示float数。如何显示浮点数?

显示浮点数可以很好地使用:

printf("%f", 1.23f);

如果数字或变量不是float,则强制转换将起作用:

int num[100];
....
printf("%f", (float) num[j]);

注意:传递给...函数(如printf())的变量值将这些值转换为double

然而,OP真正的问题似乎是,这个数字需要作为某个浮点值从文件中读取。

// int num[100];
float num[100];
...
// Age: 18.5
char buf[50];
if (fgets(buf, sizeof buf, f1) == NULL) Handle_IOError_or_EOF();
if (sscanf(buf, "Age:%f", buf, &num[j]) != 1) Handle_UnexpectedData();
printf("Age: %.1fn", num[j]);

C++:

cout << num[j] << endl;

C:

printf("%f n", num[j]);

最新更新