該程式應該使用函式結構和陣列列印選單,我的程式可以干凈地編譯,但不會在螢屏上列印任何內容。任何幫助將不勝感激。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char pizzaName[30];
char ingredients[70];
} pizza_t;
int printPizzas(pizza_t pizzaMenu[3], int numPizzas);
int main (void) {
pizza_t pizzaMenu[3];
strcpy(pizzaMenu[0].pizzaName, "Barbecue");
strcpy(pizzaMenu[0].ingredients,"Beef, chicken, bacon, barbecue sauce");
strcpy(pizzaMenu[1].pizzaName, "Carbonara");
strcpy(pizzaMenu[1].ingredients, "Mushrooms, onion, creamy sauce");
strcpy(pizzaMenu[2].pizzaName, "Ham & Cheese");
strcpy(pizzaMenu[2].ingredients, "Ham, cheese, bacon");
return 0;
}
int printPizzas(pizza_t pizzaMenu[3], int numPizzas) {
printf("\n\nPizza\t\tIngredients\n");
printf("----------------------------------------------------\n\n");
for (int i = 0; i < numPizzas; i ) {
printf("%s\t%s\n", pizzaMenu[i].pizzaName,
pizzaMenu[i].ingredients);
}
printf("\n\n");
return 0;
}
uj5u.com熱心網友回復:
上述評論的主要內容是,僅僅定義一個函式并不一定會自行執行該函式。該函式需要在某個地方呼叫,在這種情況下,您可能希望從主函式中呼叫該函式。以下是您的代碼的更新版本,其中呼叫了您的 printPizzas 函式以及其他一些改進。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
char pizzaName[30];
char ingredients[70];
} pizza_t;
void printPizzas(pizza_t pizzaMenu[3], int numPizzas); /* Changed return type to void as no actual value was going to be used */
int main (void)
{
pizza_t pizzaMenu[3];
strcpy(pizzaMenu[0].pizzaName, "Barbecue");
strcpy(pizzaMenu[0].ingredients,"Beef, chicken, bacon, barbecue sauce");
strcpy(pizzaMenu[1].pizzaName, "Carbonara");
strcpy(pizzaMenu[1].ingredients, "Mushrooms, onion, creamy sauce");
strcpy(pizzaMenu[2].pizzaName, "Ham & Cheese");
strcpy(pizzaMenu[2].ingredients, "Ham, cheese, bacon");
printPizzas(pizzaMenu, 3); /* Here is where you might print out your menu */
return 0;
}
void printPizzas(pizza_t pizzaMenu[3], int numPizzas)
{
printf("\n\nPizza\t\tIngredients\n");
printf("----------------------------------------------------\n");
for (int i = 0; i < numPizzas; i )
{
printf("%s\t%s\n", pizzaMenu[i].pizzaName, pizzaMenu[i].ingredients);
}
printf("\n\n");
return; /* FYI - when the function return type is void, this return could be omitted; just a matter of personal taste */
}
在 main 函式中,您會注意到 printPizzas 函式在程式初始化選單項之后被呼叫。呼叫中的引數與函式期望的結構陣列和陣列元素的數量相匹配。在審查您的代碼時,似乎不需要回傳任何型別的值。因此進行了調整以使回傳型別為 void 而不是 int。該函式在回傳整數值時可以正常作業,但在不需要回傳值時通常使用 void 回傳型別。
以下是運行此代碼時到終端的輸出。
@Una:~/C_Programs/Console/Pizzas/bin/Release$ ./Pizzas
Pizza Ingredients
----------------------------------------------------
Barbecue Beef, chicken, bacon, barbecue sauce
Carbonara Mushrooms, onion, creamy sauce
Ham & Cheese Ham, cheese, bacon
除此之外,您似乎已經掌握了結構的概念,只需要對函式進行更多練習并呼叫它們。
試一試,看看它是否符合您專案的精神。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/518363.html
標籤:C
