gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:08:45 27 4
gpt4 key购买 nike

我想计算体重指数并将其写入文件。我尝试在另一个函数中计算它,如您所见,但输出仅为 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com