【问题标题】:How to add up repetitive values from input in C?如何将C中输入的重复值相加?
【发布时间】:2021-04-30 01:28:10
【问题描述】:

我对 C 有点陌生。 我正在尝试制作一个购物车应用程序,该程序从包含产品和价格的 txt 文件中读取数据,由空格分隔。 然后在一个新行中放置另一个产品和一个价格(也由空格分隔)。 然后在另一个“bill.txt”文本文件中输出账单。 示例:

取自文件 (products.txt) 的输入:

Bread 2.78
cheese 4.59
vegetables 1.99
bread 1.99
Milk 0.56
cheese 2.79

输出写入另一个文件(bill.txt):

bread : 4.77 , 2 products, average-price: 2.38
cheese: 7.38 , 2 products, average-price: 3.69
milk: 0.56 , 1 products, average-price: 0.56
vegetables: 1.99 , 1 products, average-price: 1.99
total : 14.70

我的主要问题是我对如何将文本文件中的面包等重复产品的总和相加并将它们添加为数量感到困惑!面包在输入中被写入两次,但数量为 2。

通常在 java 之类的语言中,我会使用 ArrayList 并轻松解决它,但由于 C 没有 Arraylist,该怎么办?

这是我的代码:

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

int count;
struct Product
{
    char productName[30];
    double price;
};

 struct Product p1;

int main()
{
    double total = 0;

    //input file
     FILE *fp;
    fp = fopen("products.txt","r");
    //output file
    FILE *fp1 = fopen("bill.txt","w");
    if (fp == NULL || fp1 ==NULL)
    {
        perror("files didn't open");
    }
    printf("this input was written in file:\n");
    while(1)
    {
        fscanf(fp,"%s %d",&p1.productName,&p1.price);
        total = total + p1.price;
        fprintf(fp1,"%s:\t%d,  \n",p1.productName,p1.price);
        printf("%s:\t%d,  \n",p1.productName,p1.price);
        if (feof(fp))
        {
            fprintf(fp1,"Total: %d",total);
            break;
        }
}
printf("total: %d", total);
return 0;
}

有什么想法吗?

【问题讨论】:

  • 你知道你有多少产品吗?或上限?如果不是,那么您必须使您的产品列表可调整大小。另一方面,如果您事先确切知道您拥有的产品,您可以让它变得更简单。
  • 256 是一个不错的选择 ;-) 虽然我看到我在下面选择了一个无聊的 100!对于动态分配,有两个有趣的地方。在相关示例中,静态产品名称长度设置为 30。然后是产品列表的大小。首先使用静态值,让代码正常工作,然后随着有趣的练习更改为对产品列表和产品名称使用动态分配。
  • 所以你必须做不区分大小写的比较?

标签: c algorithm sorting


【解决方案1】:

您必须跟踪产品列表和总计,否则您将不得不多次迭代输入文件以获取每个产品的总计,以防产品订单混合。您可以将总计添加到您的产品结构中,并添加一个 int 来跟踪列表中有多少东西:

int itemsInList=0;
struct Product
{
    char productName[30];
    double price;
    int count;
    double total;
};

一开始您无需担心 malloc/realloc,您可以使用静态产品列表。

struct Product prodList[100];

编写一个函数,将一个项目添加到您的列表中。 像这样的东西... 此处为您提供的伪代码将不得不修复 tolower、strcmp、strcpy 位。 和未经测试的代码,如果语法/其他错误道歉!

addToList(struct Product p) 
{
    // google how to lowercase the product name
    lowname = lowercase(p.productName); // use tolower from ctype.h
    // search your list for product already
    int i;
    int found = 0;
    for(i=0;i<itemsInList;i++)
    {
        if compare(prodList[itemsInList].productName,lowname) // use strcmp
        {  
             // FOUND, add item to total, increment count, set found to true
             prodList[itemsInList].total += p.price;
             prodList[itemsInList].count++;
             found = 1;
             // we could allow loop to continue but for efficiency we end for loop now with break
             break;
        }
    }
    // if not found already add NEW entry to end of list
    if (!found) 
    {
        prodList[itemsInList].productName = lowname;   // use strcpy or strncpy is safer
        // add with correct total and count
        prodList[itemsInList].total = p.price;
        prodList[itemsInList].count = 1;
        // and increment total items in list count
        itemsInList++;
    }
}

Google 如何小写、比较和复制字符串: https://man7.org/linux/man-pages/man3/tolower.3.html https://man7.org/linux/man-pages/man3/strcmp.3.html https://man7.org/linux/man-pages/man3/strcpy.3.html

完成编写一个迭代产品列表并打印账单的函数。

void printBill(void) 
{
    // iterate list with for loop and print totals and counts
}

为了以后的练习,不使用全局变量存储数组,使用malloc/realloc进行动态内存分配。首先使用静态数组让它工作。

【讨论】:

    【解决方案2】:

    你没有 ArrayList 但你仍然有可以使用的数组是正确的

    malloc()、realloc() 和 calloc()

    另外,尝试使用 2 个数组 1 作为名称,1 作为总和,例如: 在 char** names - 你可以输入产品的名称(假设第一个是面包) double* sums - 所以第一个是所有面包的总和。

    malloc、realloc 和 calloc 使用 RAM 内存,所以一定要

    免费()

    当你完成它们时。

    【讨论】:

      【解决方案3】:

      我不是 c 程序员,但我是 dart 程序员(dart 是一种具有 c 语法的语言)所以:

      Map shoppingList = {
          "bread" : 2.45,
          "butter" : 2.35,
       };
       
      void calculateShoppingList(Map shoppingList) {
         int output = 1;
         
          for (auto const& [String key,Int val] : shoppingList) {
             output = output + val
         }
      
      
         return output
      }
      
      calculateShoppingList(shoppingList)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-09
        • 1970-01-01
        • 2019-03-16
        • 1970-01-01
        • 2016-05-22
        • 1970-01-01
        相关资源
        最近更新 更多