gpt4 book ai didi

打印 float 错误的代码以及如何按结构中的元素排序

转载 作者:太空宇宙 更新时间:2023-11-04 08:48:24 26 4
gpt4 key购买 nike

我是一名学习代码 C 的大学生,我的 C 作业(管理产品)遇到了一些问题。我下面的代码输出有问题。无论输入是什么,产品的价格总是一堆 0.00。这有什么问题??顺便说一句,如何应用这个 How to sort an array of structs in C?进入我的代码??我的程序会按价格对产品进行排序。有人可以帮我吗?那太棒了,如果代码很长,抱歉

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

void input();
void menu();
void read();

struct product
{
char code[20];
char name[50];
int quan;
float pr;
};

void menu()
{
int k;
printf("___________MENU________\n");
printf(
"1. Enter the info of your products which is saved in Products.txt\n");
printf("2. Read the file Products.txt & sort by price.\n");
printf("3. Exit");
printf("________________________\n");
printf("Enter your option: ");
fflush(stdin);
scanf("%d", &k);

switch (k)
{
case 1:
input();
break;
case 2:
read();
break;
case 3:
printf("\nTerminating");
exit(0);
break;
default:
printf("\nError! Wrong Number is Entered\nPlease Try Again\n");
break;
};
}

void input()
{
struct product proinfo[50];
FILE *fp;
int n, i;

printf("How many products need imported?\n");
scanf("%d", &n);

if ((fp = fopen("Products.txt", "wb")) == NULL )
{
printf("Error opening file!\n");
exit(0);
}

for (i = 0; i < n; i++)
{
printf("Code of product # %d: ", i + 1);
fflush(stdin);
gets(proinfo[i].code);
printf("Name: ");
gets(proinfo[i].name);
printf("Quantity: ");
scanf("%d", &proinfo[i].quan);
printf("Price: ");
scanf("%.2f", &proinfo[i].pr);

}

if (fp != NULL )
{
for (i = 0; i < n; i++)
fwrite(&proinfo[i], sizeof(struct product), 1, fp);
fclose(fp);
}

}

void read()
{
struct product a[50];
int len, t, r;

FILE *fp;
fp = fopen("Products.txt", "rb");

if (fp != NULL )
{
fseek(fp, 0, SEEK_END);
len = ftell(fp);
t = len / sizeof(struct product);
rewind(fp);
fread(&a[0], sizeof(struct product), t, fp);

for (r = 0; r < t; r++)
{
printf("%s \t %s \t %d \t %.2f\n", a[r].code, a[r].name, a[r].quan,
a[r].pr);
}
fclose(fp);
}
else
printf("No data!");
}

int main(void)
{
int a;
for (a = 0;; a++)
{
menu();
}
}

最佳答案

添加产品时,您必须使用 %f 而不是 %.2f:

scanf("%f", &proinfo[i].pr);

关于打印 float 错误的代码以及如何按结构中的元素排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20700406/

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