想知道如何将我的代码划分为单独的函数



我最近在大学开始学习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:nn");
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;
}

如何使用avg函数

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);

你可以使用它作为执行其他功能的模型

既然您正在学习C语言,那么对于您现有的代码有几个注意事项。你真正的问题似乎是"如何将我的代码划分为单独的函数"。

有两种基本方法,

  1. 学习时,通常更容易编写程序,调试并工作,然后将类似的功能分离为单独的函数,或者随着经验的增长
  2. 你了解你需要创建的功能,以及它将如何与你现有的代码接口,并简单地编写一个新的函数来满足你的需求。

在你的情况下,写你的程序,然后把它放在你面前,这样你就可以把输入计算输出功能分开,这会给你一个很好的路线图,你需要你的函数做什么。

在第一次编写程序时,您可能想要改进代码的注意事项(此处和以后)在下面的注释中列出:

#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 - %dn", 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 = %.2fn", avg);    /* always end final output with n */
}

将代码划分为函数

有了InputcomputationOutput的路线图,您可以很容易地识别与输入相关的代码——以及它需要哪些变量。

你有一个最大的数组大小为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 - %dn", 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 = %.2fn", 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 - %dn", 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

看一遍,有问题就告诉我。

最新更新