我最近開始在大學學習 C,我今天的任務是撰寫一個程式來計算一系列結構中產品的平均價格。有人告訴我,我的代碼應該分成不同的函式。如何將 printf for 回圈和 for 回圈的平均價格放在一個單獨的函式中,然后在 main() 中呼叫它?
感謝您提前回復。
#define n 2
struct products{
char name[30];
char brand[30];
double price;
int quantity;
};
int main()
{
struct products products_arr[n];
int i;
float sum,avg;
for (i=0;i<n;i )
{
printf("Enter product/s:\n\n");
printf("Enter product name: \n");
scanf("%s",products_arr[i].name);
printf("Enter product brand: \n");
scanf("%s",products_arr[i].brand);
printf("Enter product price: \n");
scanf("%lf",&products_arr[i].price);
printf("Enter product quantity: \n");
scanf("%d",&products_arr[i].quantity);
}
for (i=0;i<n;i )
{
printf("\n%s - %s - %.2lf - %d",products_arr[i].name,
products_arr[i].brand,
products_arr[i].price,
products_arr[i].quantity);
printf("\n");
}
for (i = 0; i < n; i )
{
sum = products_arr[i].price;
}
avg = sum / n;
printf("\nAverage = %.2f", avg);
return 0;
}
uj5u.com熱心網友回復:
繼承人如何做平均功能
double avg(struct products * prod, int sz){
double sum = 0;
for(int i = 0 ; i < sz; i ){
sum = prod[i].price;
}
return sum / sz;
}
注意你必須傳遞一個指向陣列開頭的指標,加上陣列的大小
現在在 main 中呼叫它
double average = avg(products_arr, n);
如果函式主體在 main 主體之后,則需要在 main 之前宣告 avg
double avg(struct products * prod, int sz);
您可以將其用作執行其他功能的模型
uj5u.com熱心網友回復:
由于您正在學習 C,因此您現有的代碼有幾個注意事項。您真正的問題似乎是“如何將我的代碼分成單獨的函式”。
有兩種基本方法,
- 學習時,通常更容易撰寫程式,對其進行除錯和作業,然后將類似的功能分成單獨的函式,或者隨著您的經驗的增長
- 您了解需要創建的功能以及它將如何與現有代碼互動,并且只需撰寫一個新功能即可滿足您的需求。
在你的情況下,撰寫你的程式,然后在你面前使用它,這樣你就可以分離Input、Computations和Output功能,這將為你提供一個很好的路線圖,說明你需要你的函式來做什么。
在第一次撰寫程式時,您可能希望改進代碼(此處和以后)的注意事項列在下面的注釋中:
#include <stdio.h>
#include <string.h>
#define N 2 /* define as many as you need - UPPERCASE */
#define MAXC 30
#define BUFSZ 1024
typedef struct products { /* add a typedef to make type use convenient */
char name[MAXC];
char brand[MAXC];
double price;
int quantity;
} products;
int main (void)
{
char buf[BUFSZ] = ""; /* read buffer */
int i = 0;
double sum = 0., avg = 0.;
products products_arr[N] = {0}; /* initialize arrays all zero */
puts ("Enter products"); /* heading before loop */
for (i = 0; i < N; i )
{
fputs ("\n Enter product name : ", stdout);
/* read user input with fgets() to consume entire line */
if (fgets (products_arr[i].name, MAXC, stdin) == NULL) {
puts ("(user canceled input)");
return 0;
}
/* trim trailing '\n' with strcspn()
* strcspn (string, "\n") // returns no. of chars to "\n"
* string[strcspn (string, "\n")] = 0; // overwrites '\n' with 0
*/
products_arr[i].name[strcspn (products_arr[i].name, "\n")] = 0;
fputs (" Enter product brand : ", stdout);
if (fgets (products_arr[i].brand, MAXC, stdin) == NULL) {
puts ("(user canceled input)");
return 0;
}
products_arr[i].brand[strcspn (products_arr[i].brand, "\n")] = 0;
fputs (" Enter product price : ", stdout);
if (fgets (buf, MAXC, stdin) == NULL) { /* read all input with fgets */
puts ("(user canceled input)");
return 0;
}
/* parse needed information from read-buffer with sscanf() */
if (sscanf (buf, "%lf", &products_arr[i].price) != 1) {
fputs ("error: invalid double value.\n", stderr);
return 1;
}
fputs (" Enter product quantity : ", stdout);
if (fgets (buf, MAXC, stdin) == NULL) { /* read all input with fgets */
puts ("(user canceled input)");
return 0;
}
if (sscanf (buf, "%d", &products_arr[i].quantity) != 1) {
fputs ("error: invalid integer value.\n", stderr);
return 1;
}
}
for (i = 0; i < N; i )
{ /* add '\n' to end of format string, don't call printf() twice */
printf ("\n%s - %s - %.2lf - %d\n", products_arr[i].name,
products_arr[i].brand,
products_arr[i].price,
products_arr[i].quantity);
sum = products_arr[i].price; /* don't waste loop, sum here */
}
avg = sum / N;
printf("\nAverage = %.2f\n", avg); /* always end final output with \n */
}
將代碼分離為函式
借助Input、Computations和Output的路線圖,初步了解將代碼分解為單獨的函式,您可以相當容易地識別與輸入相關的代碼——以及它需要哪些變數。
你有一個最大陣列大小N,你需要作為引數傳遞給你的輸入函式是產品陣列。然后輸入函式可以回傳讀取的產品數量(可以小于N)。發生錯誤時,您可以回傳負值,或者只是回傳發生錯誤時成功讀取的產品數量,保留您當時收集的資料。
對于您的輸入功能,您可以執行以下操作:
/** read up to a max of N products from stdin
* return number of elements read on success (can be less than N),
* otherwise returns -1 if user cancels input with manual EOF
*/
int read_products (products *products_arr)
{
char buf[BUFSZ] = ""; /* read buffer */
int i = 0;
puts ("Enter products"); /* heading before loop */
for (i = 0; i < N; i )
{
fputs ("\n Enter product name : ", stdout);
/* read user input with fgets() to consume entire line */
if (fgets (products_arr[i].name, MAXC, stdin) == NULL) {
puts ("(user canceled input)");
return 0;
}
/* trim trailing '\n' with strcspn() // How?
* strcspn (string, "\n") // returns no. of chars to "\n"
* string[strcspn (string, "\n")] = 0; // overwrites '\n' with 0
*/
products_arr[i].name[strcspn (products_arr[i].name, "\n")] = 0;
fputs (" Enter product brand : ", stdout);
if (fgets (products_arr[i].brand, MAXC, stdin) == NULL) {
puts ("(user canceled input)");
return -1;
}
products_arr[i].brand[strcspn (products_arr[i].brand, "\n")] = 0;
fputs (" Enter product price : ", stdout);
if (fgets (buf, MAXC, stdin) == NULL) { /* read all input with fgets */
puts ("(user canceled input)");
return -1;
}
/* parse needed information from read-buffer with sscanf() */
if (sscanf (buf, "%lf", &products_arr[i].price) != 1) {
fputs ("error: invalid double value.\n", stderr);
return i;
}
fputs (" Enter product quantity : ", stdout);
if (fgets (buf, MAXC, stdin) == NULL) { /* read all input with fgets */
puts ("(user canceled input)");
return i;
}
if (sscanf (buf, "%d", &products_arr[i].quantity) != 1) {
fputs ("error: invalid integer value.\n", stderr);
return 1;
}
}
return i;
}
對于您的平均功能,除了產品陣列之外,您還需要傳遞陣列中包含的產品數量(因為它可以小于N)。您始終將函式的回傳型別與回傳的值的型別相匹配。在這里你可以這樣做:
/** computes the average of nelem product price
* returns average
*/
double products_avg (products *products_arr, int nelem)
{
int i = 0; /* initialize variables */
double sum = 0;
for (; i < nelem; i ) /* loop nelem times */
{
sum = products_arr[i].price; /* sum price */
}
return sum / nelem; /* return average */
}
最后,您的輸出功能可以列印單個產品。同樣,除了陣列之外,您還需要傳遞陣列中的產品數量。由于輸出函式不需要回傳值,它可以是型別void,因為不需要指示成功/失敗,并且您不依賴任何回傳的計算值,例如
/** prints individual product's name, brand, price & quantity */
void products_print (products *products_arr, int nelem)
{
int i = 0; /* initialize variables */
for (; i < nelem; i ) /* loop nelem times */
{ /* add '\n' to end of format string, don't call printf() twice */
printf ("\n%s - %s - %.2lf - %d\n", products_arr[i].name,
products_arr[i].brand,
products_arr[i].price,
products_arr[i].quantity);
}
}
總而言之,您的程式分離為函式可能如下所示:
#include <stdio.h>
#include <string.h>
#define N 2 /* define as many as you need - UPPERCASE */
#define MAXC 30
#define BUFSZ 1024
typedef struct products { /* add a typedef to make type use convenient */
char name[MAXC];
char brand[MAXC];
double price;
int quantity;
} products;
/* function prototypes (will go in header file later) */
int read_products (products *products_arr);
double products_avg (products *products_arr, int nelem);
void products_print (products *products_arr, int nelem);
int main (void)
{
int nelem = 0;
double avg = 0.;
products products_arr[N] = {0}; /* initialize arrays all zero */
nelem = read_products (products_arr); /* read products assign return */
if (nelem < 1) { /* validate read_products return */
return 1;
}
avg = products_avg (products_arr, nelem); /* compute average */
products_print (products_arr, nelem); /* output products */
printf("\nAverage = %.2f\n", avg); /* always end final output with \n */
}
/** read up to a max of N products from stdin
* return number of elements read on success (can be less than N),
* otherwise returns -1 if user cancels input with manual EOF
*/
int read_products (products *products_arr)
{
char buf[BUFSZ] = ""; /* read buffer */
int i = 0;
puts ("Enter products"); /* heading before loop */
for (i = 0; i < N; i )
{
fputs ("\n Enter product name : ", stdout);
/* read user input with fgets() to consume entire line */
if (fgets (products_arr[i].name, MAXC, stdin) == NULL) {
puts ("(user canceled input)");
return 0;
}
/* trim trailing '\n' with strcspn() // How?
* strcspn (string, "\n") // returns no. of chars to "\n"
* string[strcspn (string, "\n")] = 0; // overwrites '\n' with 0
*/
products_arr[i].name[strcspn (products_arr[i].name, "\n")] = 0;
fputs (" Enter product brand : ", stdout);
if (fgets (products_arr[i].brand, MAXC, stdin) == NULL) {
puts ("(user canceled input)");
return -1;
}
products_arr[i].brand[strcspn (products_arr[i].brand, "\n")] = 0;
fputs (" Enter product price : ", stdout);
if (fgets (buf, MAXC, stdin) == NULL) { /* read all input with fgets */
puts ("(user canceled input)");
return -1;
}
/* parse needed information from read-buffer with sscanf() */
if (sscanf (buf, "%lf", &products_arr[i].price) != 1) {
fputs ("error: invalid double value.\n", stderr);
return i;
}
fputs (" Enter product quantity : ", stdout);
if (fgets (buf, MAXC, stdin) == NULL) { /* read all input with fgets */
puts ("(user canceled input)");
return i;
}
if (sscanf (buf, "%d", &products_arr[i].quantity) != 1) {
fputs ("error: invalid integer value.\n", stderr);
return 1;
}
}
return i;
}
/** computes the average of nelem product price
* returns average
*/
double products_avg (products *products_arr, int nelem)
{
int i = 0; /* initialize variables */
double sum = 0;
for (; i < nelem; i ) /* loop nelem times */
{
sum = products_arr[i].price; /* sum price */
}
return sum / nelem; /* return average */
}
/** prints individual product's name, brand, price & quantity */
void products_print (products *products_arr, int nelem)
{
int i = 0; /* initialize variables */
for (; i < nelem; i ) /* loop nelem times */
{ /* add '\n' to end of format string, don't call printf() twice */
printf ("\n%s - %s - %.2lf - %d\n", products_arr[i].name,
products_arr[i].brand,
products_arr[i].price,
products_arr[i].quantity);
}
}
示例使用/輸出
這兩個示例的作業方式完全相同,并且會產生相同的輸出,例如:
$ ./bin/structavg
Enter products
Enter product name : foo
Enter product brand : fink
Enter product price : 23.44
Enter product quantity : 10
Enter product name : bar
Enter product brand : blink
Enter product price : 26.66
Enter product quantity : 10
foo - fink - 23.44 - 10
bar - blink - 26.66 - 10
Average = 25.05
看看事情,如果你有問題,請告訴我。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/473738.html
標籤:C
上一篇:有誰知道我的程式為什么會崩潰?
