【问题标题】:C - Displaying the parts in ascending order by part numberC - 按零件编号升序显示零件
【发布时间】:2014-09-24 22:31:50
【问题描述】:

我是新来的,所以我不知道我是否正确发布了这个。我做了教练告诉我们为这个项目做的所有事情,但最后一个让我难过,因为我们从来没有在课堂上讨论过排序。它说,“修改 print() 函数,使其显示按零件编号升序排序的零件。”我试图翻阅这本书和互联网,但我只是让自己变得更加困惑。谁能帮我?这是我的代码:

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define NAME_LEN 25
#define MAX_PARTS 100

struct part {
int number;
char name[NAME_LEN + 1];
int on_hand;
float price;
};

int find_part(int number, const struct part inv[], int np);
void insert(struct part inv[], int *np);
void search(const struct part inv[], int np);
void update(struct part inv[], int np);
void print(const struct part inv[], int np);
int read_line(char [], int);

/**************************************************************
 * main:    Prompts the user to enter an operation code,      *
 *          then calls a function to perform the requested    *
 *          action. Repeats until the user enters the         *
 *          command 'q'. Prints an error message if the user  *
 *          enters an illegal code.                           *
 **************************************************************/
int main(void)
{   
char code;
struct part inventory[MAX_PARTS];
int num_parts = 0;

for (;;)
{
    printf("Enter operation code: ");
    scanf(" %c", &code);
    while (getchar() != '\n')    /* skips to end of line */
    {
        ;
    }

    switch (code)
    {
        case 'i':
            insert(inventory, &num_parts);
            break;

        case 's': 
            search(inventory, num_parts);
            break;

        case 'u':
            update(inventory, num_parts);
            break;

        case 'p': 
            print(inventory, num_parts);
            break;

        case 'q':
            return 0;

        default:
            printf("Illegal code\n");
            break;
    }

    printf("\n");
}
}

/************************************************************
 * find_part:   Looks up a part number in the inv array.    *
 *              Returns the array index if the part number  *
 *              is found; otherwise, returns -1.            *
 ************************************************************/
int find_part(int number, const struct part inv[], int np)
{
int i;

for (i = 0; i < np; i++)
{
    if (inv[i].number == number)
    {
        return i;
    }
}

return -1;
}

/****************************************************************
 * insert: Prompts the user for information about a new         *
 *               part and then inserts the part into the inv    *
 *               array. Prints an error message and returns     *
 *               prematurely if the part already exists or the  *
 *               array is full.                                 *
 ****************************************************************/
void insert(struct part inv[], int *np)
{
int part_number;

if (*np == MAX_PARTS)
{
    printf("Database is full; can't add more parts.\n");
    return;
}

printf("Enter part number: ");
scanf("%d", &part_number);

if (find_part(part_number, inv, *np) >= 0)
{
    printf("Part already exists.\n");
    return;
}

inv[*np].number = part_number;
printf("Enter part name: ");
read_line(inv[*np].name, NAME_LEN);
printf("Enter quantity on hand: ");
scanf("%d", &inv[*np].on_hand);
printf("Enter the price of the item: ");
scanf("%f", &inv[*np].price);
(*np)++;
}

/************************************************************
 * search:  Prompts the user to enter a part number, then   *
 *          looks up the part in the inv array. If the      *
 *          part exists, prints the name and quantity on    *
 *          hand; if not, prints an error message.          *
 ************************************************************/
void search(const struct part inv[], int np)
{
int i, number;


printf("Enter part number: ");
scanf("%d", &number);

i = find_part(number, inv, np);
if (i >= 0)
{
    printf("Part name: %s\n", inv[i].name);
    printf("Quantity on hand: %d\n", inv[i].on_hand);
    printf("Item Price: %.2f\n", inv[i].price);
}
else
{
    printf("Part not found.\n");
}
}

/*************************************************************
 * update:  Prompts the user to enter a part number.         *
 *          Prints an error message if the part can't be     *
 *          found in the inv array; otherwise, prompts the   *
 *          user to enter change in quantity on hand and     *
 *          updates the array.                               *
 *************************************************************/
void update(struct part inv[], int np)
{
int i, number, change, userChoice, changePartNum;
float changePrice;
char *changeName[] = {""};

printf("Enter part number: ");
scanf("%d", &number);

i = find_part(number, inv, np);
if (i >= 0)
{   
    printf("Enter your selection to edit this particular part:\n"
            "\t\t Type 1 to change the Part Number\n"
            "\t\t Type 2 to change the Part Name\n"
            "\t\t Type 3 to change the Price\n"
            "\t\t Type 4 to change the Quantity on Hand\n"
            "\t\t Type 5 to exit without making changes\n\n"
            "\t\t Enter your choice here: ");
    scanf("%d", &userChoice);
    switch ( userChoice )
        {
            //printf("Would you like to change the Part Number? \nType 1 for yes or 2 for no.");
            //scanf("%d", &userChoice);
            case 1:
                    printf("Enter new part number: ");
                    scanf("%d", &changePartNum);
                    inv[i].number = changePartNum;
                    printf("Change part num: %d\n", changePartNum);
                    printf("inv[i].number: %d\n", inv[i].number);
                    break;

            //printf("Would you like to change the Part Name? \nType 1 for yes or 2 for no.");
            //scanf("%d", &userChoice);
            case 2:
                    printf("Enter new name of part: ");
                    scanf("%s", changeName);
                    printf("Change part name: %s\n", changeName);
                    //strcpy (*changeName, inv[i].name[NAME_LEN + 1]);
                    //printf("&inv[i].name[NAME_LEN + 1]: %d\n", &inv[i].name[NAME_LEN + 1]);
                    break;


            //printf("Would you like to change the price? \nType 1 for yes or 2 for no.");
            //scanf("%d", &userChoice);
            case 3:
                    printf("Enter change in item price: ");
                    scanf("%f", &changePrice);
                    inv[i].price = changePrice;
                    break;

            //printf("Would you like to change the quantity on hand? \nType 1 for yes or 2 for no.");
            //scanf("%d", &userChoice);
            case 4:
                    printf("Enter change in quantity on hand: ");
                    scanf("%d", &change);
                    inv[i].on_hand = change;
                    break;
            case 5:
                printf("Exiting the editor.");
                break;
            default:
                printf("Your choice is not on the list.");
                break;
        }   
} 
else
{
    printf("Part not found.\n");
}
}

/************************************************************
 * print:   Prints a listing of all parts in the inv array, *
 *          showing the part number, part name, and         *
 *          quantity on hand. Parts are printed in the      *
 *          order in which they were entered into the       *
 *          array.                                          *                                                           *
 ************************************************************/
void print(const struct part inv[], int np)
{
int i;

printf("Part Number  Part Name       "
             "Quantity on Hand    "
             "  Price\n");
for (i = 0; i < np; i++)
{
    printf("%7d\t\t    %-5s%31d\t%.2f\n", inv[i].number,
                 inv[i].name, inv[i].on_hand, inv[i].price);
}
}

/*************************************************************
 * read_line:   Skips leading white-space characters, then   *
 *              reads the remainder of the input line and    *
 *              stores it in str.   Truncates the line if its *
 *              length exceeds n.   Returns the number of    *
 *              characters stored.                           *
 *************************************************************/
int read_line(char str[], int n)
{
int ch = 0;
int i = 0;

while (isspace (ch = getchar()))
{
    ;
}

while (ch != '\n' && ch != EOF)
{
    if (i < n)
    {
        str[i++] = ch;
    }

    ch = getchar();
}

str[i] = '\0';

return i;
}

【问题讨论】:

  • 您的作业是否要求您制定自己的排序程序?如果没有,您可能想查看 qsort 这是一个 c 库函数。
  • @MichaelPetch 讲师没有具体说明他想要什么。我们甚至从未讨论过排序。这就是为什么我对为什么它在任务中感到困惑。
  • @InSeriousNeedOfAspirin 给你的教授发电子邮件是最好的选择。
  • @remyabel 我做了,他仍然想要排序。
  • 如果您只发布代码的基本部分,您将更快、更多地得到这个问题的答案。如果我们必须通读 500 行代码,我们很乐意提供帮助。此外,明确说明您的程序正在做什么与您希望它做什么。

标签: c function sorting inventory


【解决方案1】:

如果您的教授允许您使用标准库中的函数,请查看C library function to do sort,它提供了一个向您展示如何使用qsort() 的答案。如果您使用的是 linux,您还可以通过 man qsort 获取有关该函数(和其他标准库函数)的文档。如果您不在 linux 上,请查看各种在线手册页。

如果没有,您的教授可能希望您自己进行研究。通常,冒泡排序算法因其简单性而被教授给初学者。 rosettacode 提供了冒泡排序的伪代码:

repeat
    hasChanged := false
    decrement itemCount
    repeat with index from 1 to itemCount
        if (item at index) > (item at (index + 1))
            swap (item at index) with (item at (index + 1))
            hasChanged := true
until hasChanged = false

请注意,在您的打印函数中,您已经拥有所需的一切,数组及其长度。您通过循环并打印出所有成员变量来证明这一点。现在您只需要编写排序算法。该算法需要的一件事是比较器功能。你说你需要按零件号排序。这意味着您的比较器函数可能如下所示:

int compare(struct part a, struct part b)
{
    return (a.number < b.number);
}

对于qsort()

qsort(inv, np, sizeof(part), compare);

在您的排序算法中(您应该自己编写):

if (item.number at index) > (item.number at (index + 1))

【讨论】:

    猜你喜欢
    • 2021-04-12
    • 2013-01-25
    • 1970-01-01
    • 2011-10-24
    • 1970-01-01
    • 1970-01-01
    • 2011-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多