c - C 语言的文件处理计算

标签 c file file-handling

我想计算体重指数并将其写入文件。我尝试在另一个函数中计算它,如您所见,但输出仅为 0。然后我尝试了不同的函数,如 int 计算返回w/h*h 但他们都没有给我正确的答案。我找不到其他方法。

#include <stdio.h>
struct person
{
    int personId;
    double height;
    double weight;
    double BMI;
}; 

void calculate (double h, double w)
{
    struct person p1;
    p1.BMI = w / h*h ;
}
void write () {
FILE *file;
struct person p1;
file = fopen("bmi.txt","w");
if (file == NULL)
{
    printf("Error");
}
else
{
    printf("Person ID: "); scanf("%d",&p1.personId);
    printf("Height: "); scanf("%lf",&p1.height);
    printf("Weight: "); scanf("%lf",&p1.weight);
    calculate(p1.height,p1.weight);
    fwrite(&p1,sizeof(p1),1,file);

 }
fclose(file);
}

void read() {
FILE *file;
struct person p1;
file = fopen("bmi.txt","r");
if (file == NULL)
{
    printf("Error");
}
else
{
    while (!feof(file))
    {
        fread(&p1,sizeof(p1),1,file);
        printf("Person ID: %d\n",p1.personId);
        printf("Height: %f\n",p1.height);
        printf("Weight: %f\n",p1.weight);
        printf ("BMI: %f\n",p1.BMI);
    }
}
fclose(file);
}

int main () {
write();
read();
}

最佳答案

#include <stdio.h>

struct person {
    int personId;
    double height;
    double weight;
    double BMI;
}; 

double calculate (double h, double w){//change to return result
    return w / (h*h);//Need parentheses
}

void write_person(void){
    FILE *file;
    struct person p1;

    if ((file = fopen("bmi.dat", "ab")) == NULL){
        perror("fopen in write_person");
    } else {
        printf("Person ID : "); scanf("%d", &p1.personId);
        printf("Height(m) : "); scanf("%lf",&p1.height);
        printf("Weight(kg): "); scanf("%lf",&p1.weight);
        p1.BMI = calculate(p1.height,p1.weight);
        fwrite(&p1, sizeof(p1), 1, file);
        fclose(file);//Should be into else-block
     }
}

void read_person(void){
    FILE *file;
    struct person p1;

    if ((fopen("bmi.dat","rb")) == NULL){
        perror("fopen in read_person");
    } else {
        while (fread(&p1, sizeof(p1), 1, file) > 0){//don't use !feof(file) because EOF occurs at fread So Display of incorrect data.
            printf("Person ID: %d\n", p1.personId);
            printf("Height   : %.3f(m)\n", p1.height);
            printf("Weight   : %.1f(kg)\n", p1.weight);
            printf("BMI      : %.2f\n\n", p1.BMI);
        }
        fclose(file);
    }
}

int main (void) {
    write_person();
    read_person();

    return 0;
}

关于c - C 语言的文件处理计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37102676/

相关文章:

将单词的所有副本大写 : why does this code fail when it's in its own function?

python - 计算文件中字母的频率并写入输出文件python

python - 文件只写在我的程序末尾

perl - ssh 问题 - 没有这样的文件或目录

java - 如何使用java将文件和文件夹列表存储在列表或设置中?

c - 通过 TCP-IPv6 连接进行数据传输

c - void(*) void 和 int(*) int 在 C 中是什么意思?

php - 检查文件(robots.txt,favicon.ico)到网站 php

c - Linux select() 不阻塞

c - 64 位乘法哈希