c - 如何在这段代码中使用自定义函数?

标签 c windows

我可以在这段代码中使用自定义函数吗?我的作业要求我使用自定义函数,但我对此不太擅长,我该怎么做? 这是一个收银程序,要求用户提供他们想要购买的产品的商品代码。

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

int main(void)
{
    int i,j = 0, code, amt, key, lines = 0;
    int id[100], stock[100], k = 0;
    char name[100][20], product[100], newstock[100];
    float price[100], sum;
    float total = 0;  
    char ipname[100][20];
    int quantity[100], ch;
    float ipprice[100];
    float ipsub[100],pay,balance;

    FILE *fp1;

    fp1 = fopen("Fruit.txt", "r");

    if(fp1 == NULL)
    {
        printf("ERROR in opening file\n");
        return 1;
    }
    else
    {
        while((ch = getc(fp1))!= EOF)
        {
            if(ch == '\n')
                lines++;
        }
    }

    fclose(fp1);

    fp1 = fopen("Fruit.txt","r");

    if(fp1 == NULL)
    {
        printf("ERROR in opening file\n");
        return 1;
    }
    else
    {
        for(i = 0; i < lines; i++)
        {
            fgets(product, sizeof(product), fp1);
            id[i] = atoi(strtok(product, ","));
            strcpy(name[i], strtok(NULL, ","));
            price[i] = atof(strtok(NULL, ","));
            stock[i]=atoi(strtok(NULL,"\n"));
        }
    }

    fclose(fp1);

    FILE *fp3;

    fp3 = fopen("Stock.txt", "r");

    if(fp3!=NULL)
    {
        for(i = 0; i < lines; i++)
        {
            fgets(newstock, sizeof(newstock), fp3);

            id[i] = atoi(strtok(newstock, ","));
            strcpy(name[i], strtok(NULL, ","));
            price[i] = atof(strtok(NULL, ","));
            stock[i] = atoi(strtok(NULL, "\n"));
        }
    }

    fclose(fp3);

    printf("=============================================================\n");

    for(i = 0; i < lines; i++)
    { 
        printf("%d:%-10s\t", i +1, name[i]);
    }

    printf("\n\n%-5s%-20s%-15s%-10s%s\n", "No.", "Product", "Price", "Quantity", "Subtotal");
    printf("%-5s%-20s%-15s%-10s%s\n", "===", "=======", "=====", "========", "========");

    do
    {  
        k = 0;
        system("cls");
        printf("=============================================================\n");

        for(i = 0; i < lines; i++)
        {
            printf("%d:%-10s\t", i +1, name[i]);
        }

        printf("\n\n%-5s%-20s%-15s%-10s%s\n", "No.", "Product", "Price", "Quantity", "Subtotal");
        printf("%-5s%-20s%-15s%-10s%s\n", "===", "=======", "=====", "========", "========");

        if(j > 0)
        {
            for(k = 0; k < j; k++)
            {
                printf("%-5d%-20sRM%-13.2f%-10dRM%.2f\n", k +1, ipname[k], ipprice[k], quantity[k], ipsub[k]);
            }
        }

        sum = 0;
        amt = 0;

        printf("\nProduct code:");
        scanf("%d", &code);

        i = code -1;

        if(i < lines && i >= 0)
        {
            printf("Quantity:");
            scanf("%d", &amt);
            stock[i] = stock[i] -amt;

            system("cls");

            sum = price[i] *amt;
            total = total + sum;
            ipprice[j] = price[i];

            strcpy(ipname[j], name[i]);

            quantity[j] = amt;
            ipsub[j] = sum;

            printf("=============================================================\n");

            for(i = 0; i < lines; i++)
            {
                printf("%d:%-10s\t", i +1, name[i]);
            }

            printf("\n\n%-5s%-20s%-15s%-10s%s\n", "No.", "Product", "Price", "Quantity", "Subtotal");
            printf("%-5s%-20s%-15s%-10s%s\n", "===", "=======", "=====", "========", "========");

            for(k = 0; k <= j; k++)
            {
                printf("%-5d%-20sRM%-13.2f%-10dRM%.2f\n", k +1, ipname[k], ipprice[k], quantity[k], ipsub[k]);
            }

            printf("\nPress ESC on keyboard to finalize the bill or Press any key continue...\n");

            j++;

            key = _getch();
        }
        else
        {
            system("cls");

            printf("=============================================================\n");

            for(i = 0; i < lines; i++)
            { 
                printf("%d:%-10s\t", i +1, name[i]);
            }

            printf("\n\n%-5s%-20s%-15s%-10s%s\n", "No.", "Product", "Price", "Quantity", "Subtotal");
            printf("%-5s%-20s%-15s%-10s%s\n", "===", "=======", "=====", "========", "========");

            if(j > 0)
            {
                for(k = 0; k < j; k++)
                {
                    printf("%-5d%-20sRM%-13.2f%-10dRM%.2f\n", k +1, ipname[k], ipprice[k], quantity[k], ipsub[k]);
                }
            }

            printf("\nInvalid product code entered, press any key to try again or press esc to finalize   bill...\n\n");
        }
    } while(key != 27);

    do
    {
        system("cls");

        printf("=============================================================\n");

        for(i = 0; i < lines; i++)
        {
            printf("%d:%-10s\t",i+1,name[i]);
        }

        printf("\n\n%-5s%-20s%-15s%-10s%s\n", "No.", "Product", "Price", "Quantity", "Subtotal");
        printf("%-5s%-20s%-15s%-10s%s\n", "===", "=======", "=====", "========", "========");

        for(k = 0; k < j; k++)
        {
            printf("%-5d%-20sRM%-13.2f%-10dRM%.2f\n", k +1, ipname[k], ipprice[k], quantity[k], ipsub[k]);
        }

        printf("\nGrand Total = RM%.2f\n",total);
        printf("\nPayment = RM");
        scanf("%f", &pay);

        if(pay >= total)
        {
            balance = pay - total;
            printf("\nBalance = RM%.2f\n", balance);
        }
        else
        {
            printf("\nInsufficient payment, Please enter larger amount!\nPress any key...");

            getch();
        }

    }while(pay < total);

    FILE *fp2;
    fp2 = fopen("receipt.txt", "w");

    if(fp1 == NULL)
    {
        printf("ERROR in opening file\n");
        return 1;
    }

    time_t now;
    time(&now);

    fprintf(fp2,"\n\n%-5s%-20s%-15s%-10s%s\n", "No.", "Product", "Price", "Quantity", "Subtotal");
    fprintf(fp2,"%-5s%-20s%-15s%-10s%s\n", "===", "=======", "=====", "========", "========");

    for(k = 0; k < j; k++)
    {
        fprintf(fp2,"%-5d%-20sRM%-13.2f%-10dRM%.2f\n", k +1, ipname[k], ipprice[k], quantity[k], ipsub[k]);
    }

    fprintf(fp2,"\n\nGrand Total = RM%.2f\n", total);
    fprintf(fp2,"Payment = RM%.2f\n", pay);
    fprintf(fp2,"Balance = RM%.2f\n", balance);

    fclose(fp2);

    fp3 = fopen("Stock.txt", "w");

    if(fp3 == NULL)
    {
        printf("ERROR in updating stock file\n");
        return 1;
    }
    else
    {
        for(i = 0; i < lines; i++)
        {
            fprintf(fp3,"%d,%s,%.2f,%d\n", id[i], name[i], price[i], stock[i])
        }
    }

    fclose(fp1);

    return 0;
}

txt文件的内容

18156,Apple,1.49,73
45776,Aprikot,1.59,23
73191,Avocado,2.49,63
72829,Banana,2.99,27
74084,Blueberry,5.49,36
79800,Coconut,3.49,80
16611,Grape,8.99,42
62690,Grapefruit,2.19,34
47089,Guava,4.99,42
70412,Jackfruit,19.99,29
44640,Kiwifruit,2.15,38
94768,Lemon,0.99,42
86240,Mango,3.99,62
78697,Orange,1.69,23
74470,Papaya,4.49,23
23959,Pear,2.49,36
78862,Pineapple,2.99,71
82943,Pomegranate,4.35,19
56180,Pomelo,12.99,72
67712,Starfruit,2.79,59
33974,Strawberry,13.99,31
45584,Watermelon,6.88,21

最佳答案

首先,也是最重要的一点,扔掉你的笔记,给自己找一本好的 C 编程书。这里The Definitive C Book Guide and List你可以找到一个好的 list ,你可以有一个好主意。

只是关于函数的基本概念。尝试确定您将一次又一次需要的代码,并将该代码放入一个函数中,这样程序就会很小,易于理解,并且您不必再次编写它。 ,在您的代码中,我看到此代码被使用了多次:

        printf("=============================================================\n");

        for(i = 0; i < lines; i++)
        { 
            printf("%d:%-10s\t", i +1, name[i]);
        }

        printf("\n\n%-5s%-20s%-15s%-10s%s\n", "No.", "Product", "Price", "Quantity", "Subtotal");
        printf("%-5s%-20s%-15s%-10s%s\n", "===", "=======", "=====", "========", "========");

所以将其放入这样的函数中:

void PrintNewBillHeader ()
{
            printf("=============================================================\n");

            for(i = 0; i < lines; i++)
            { 
                printf("%d:%-10s\t", i +1, name[i]);
            }

            printf("\n\n%-5s%-20s%-15s%-10s%s\n", "No.", "Product", "Price", "Quantity", "Subtotal");
            printf("%-5s%-20s%-15s%-10s%s\n", "===", "=======", "=====", "========", "========");
}

然后,无论您在何处执行这些步骤,只需调用此函数 PrntNewBillHeader() 即可。简单。

一开始,您正在从文件中读取数据,并且它已被调用两次。因此,创建一个新函数 ReadFileData() 并将读取代码放入该函数中。但在这里你必须传递文件名和要存储数据的数组。所以这将像这样完成:

int ReadFileData (char * pFileName, char * name, float *pPrice, float *pStock)
{
    /**Do declare the variable to be use in this function**/

    fp1 = fopen("Fruit.txt","r");

    if(fp1 == NULL)
    {
        return -1;
    }
    else
    {
        for(i = 0; i < lines; i++)
        {
            fgets(product, sizeof(product), fp1);
            id[i] = atoi(strtok(product, ","));
            strcpy(name[i], strtok(NULL, ","));
            price[i] = atof(strtok(NULL, ","));
            stock[i]=atoi(strtok(NULL,"\n"));
        }
    }

    fclose(fp1);

    return 1;
}

我希望您一定已经有了一定的想法。

尝试通过一次删除一个冗余代码来拆分主函数。

希望这有帮助。

关于c - 如何在这段代码中使用自定义函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25472360/

相关文章:

c - 如何使用递归函数计算从 1 开始到 n 结束的连续整数的总和

c - 如何创建一个通用函数来替换数组中的元素?

windows - 如何从 CLI 在 Windows 上将 AC3 转换为 AAC

windows - 以纯文本格式导出注册表

windows - 在使用 native OpenSSH 的 ssh-agent 配置良好的 Windows 10 上,如何让 git 的实现使用配置的 ssh-agent?

c - 无法使用 C30 编译器复制 PIC24FJ256GB206 中的数组

c - 跳过空格并检测行尾?

c - 延迟函数可以在 64 位编译器的 C 语言中工作吗?

windows - 模拟物理键盘按下的脚本,以便 PC 保持唤醒状态

c# - 如何扩展ms-explorer自动处理 "connected files"/sidecar files/xmp属于jpg?