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

标签 c sorting struct floating-point

我是一名学习代码 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/

相关文章:

c - 在 C 中读取 1 GB 二进制文件花费的时间太长

c - 使用数组时 C 中的段错误

go - 为结构字段分配新值

java - 无法在 JPanel 中画线

c++ - 基数排序 base 256 性能

c - 在 C 中通过指针为结构中的变量赋值

c - 未分配的变量具有随机值

c - C中的高精度除法

c - 有趣的可执行文件二进制转储

javascript - 使用tinysort按attr值排序在desc中不起作用