【发布时间】:2014-12-12 03:03:30
【问题描述】:
这个问题可能很烦人,但我正在尝试以我最容易在心理上处理它的方式编写代码,此时它不需要调用函数。我正在将我的教授示例代码改写成我自己的,但是在将它存储到什么时遇到问题?他使用指针,但我只是不知道如何/在哪里声明它。
如果这个问题的措辞有误,我深表歉意。不幸的是,我是那些在编程方面没有“明白”的人之一。
我的教授们:
#include <stdio.h>
#include <stdlib.h>
/* Program that computes the average salary of the employees with an age equal or greater
than x, x is passed as a parameter to the main function. Employee is a structure with two
fields: age and salary. */
struct employee {
int age;
float salary;
};
void readValues(struct employee *EMP, int n ) {
int i;
for(i=0; i<n; i++) {
printf("Employee %i\n", i+1);
printf("\tAge: ");
scanf("%i", &EMP[i].age);
printf("\tSalary: ");
scanf("%f", &EMP[i].salary);
}
}
float getAvg(struct employee *EMP, int minAge, int n ) {
int i, nE = 0;
float sum=0;
for(i=0; i<n; i++) {
if(EMP[i].age >= minAge) {
sum = sum + EMP[i].salary;
nE = nE + 1;
}
}
return sum/nE;
}
int main(int argc, char *argv[]) {
int x, n;
struct employee E[100];
if (argc<3) {
printf("Error: Some parameters missing.\n");
return -1;
}
x = atoi(argv[1]);
n = atoi(argv[2]);
readValues(E, n);
float avg = getAvg(E, x, n);
printf("Avg. Salary = %.2f\n", avg);
return 0;
}
我的尝试:
#include <stdio.h>
#include <stdlib.h>
#define minage 20
struct employee{
int age;
float salary;
};
int main()
{
struct employee emp = {0};
int i, n, numb=0, sum=0, avg;
printf("How many employees do you have today?\n");
scanf("%i", n);
for(i=0; i<n; i++)
{
printf("Employee %i", i+1);
printf("Age:\n");
scanf("%i", &emp[i].age);
printf("Salary:\n");
scanf("%f", &emp[i].salary);
}
if (emp[i].age >= minage)
{
for(i=0, i<n; i++){
sum = sum + emp[i].salary
numb = numb + 1
}
}
avg = sum / numb;
printf("The average salary is %i\n", avg);
}
【问题讨论】:
-
emp只有一个对象。struct employee *emp;=>scanf("%i", &n);=>emp = malloc(n*sizeof(struct employee)); -
和
if (emp[i].age >= minage)进入for循环。 -
就像你的教授一样:
struct employee emp[100]
标签: c pointers structure declare