[英]Using array of struct in a function?
我正在尝试编写一个函数,该函数更改struct数组中元素的一个值,但是它不起作用,该函数不执行任何操作。 我究竟做错了什么?
输入:
300
9
1999
1050
301
5
2000
1200
20
预期产量:
300 1260
实际输出:无
#include <stdio.h>
typedef struct
{int codice;
int mese;
int anno;
int stipendio;}
dipendente;
void aumento (dipendente a[], int dim, int n){
int i;
for (i=0; i<dim; i++)
{if (a[i].anno<2000) a[i].stipendio=a[i].stipendio+(a[i].stipendio*n)/100;;
if (a[i].anno==2000)
{if (a[i].mese<5)
a[i].stipendio=a[i].stipendio+(a[i].stipendio*n)/100;}}
}
int main () {
int i;
int p;
dipendente a[2];
for (i=0; i<2; i++){
scanf("%d",&a[i].codice);
scanf("%d",&a[i].mese);
scanf("%d",&a[i].anno);
scanf("%d",&a[i].stipendio);
}
scanf("%d", &p);
aumento (a, 2, p);
for (i=0; i<2; i++)
{if(a[i].stipendio>1200)
printf("%d %d", a[i].codice, a[i].stipendio);}
return 0; }
有两个问题。
正如@nm在注释中指出的: if (a[i].anno=2000)
正在执行赋值并且始终为true(因为2000
为true)。 您要比较。 if (a[i].anno == 2000)
, if (a[i].anno == 2000)
使用double ==
正如@SamiHult在注释中指出的:对于任何0 <= n && n < 100
, n/100
始终为0,因为n
是int
。 使用double
或float
可以进行浮点运算。 或如@alk所指出的,您可以先相乘然后相除,这样就可以保持整数数学(a[i].stipendio * n) / 100
这是很好的代码,但是缩进只是很痛。
修复这些错误后:
#include <stdio.h>
typedef struct {
int codice;
int mese;
int anno;
int stipendio;
} dipendente;
void aumento(dipendente a[], int dim, int n) {
int i;
for (i = 0; i < dim; i++) {
if (a[i].anno < 2000) {
a[i].stipendio = a[i].stipendio + a[i].stipendio * ((double)n / 100);
}
if (a[i].anno == 2000) {
if (a[i].mese < 5) {
a[i].stipendio = a[i].stipendio + a[i].stipendio * ((double)n / 100);
}
}
}
}
int main() {
int i;
int p;
dipendente a[2];
for (i = 0; i < 2; i++){
scanf("%d", &a[i].codice);
scanf("%d", &a[i].mese);
scanf("%d", &a[i].anno);
scanf("%d", &a[i].stipendio);
}
scanf("%d", &p);
aumento(a, 2, p);
for (i = 0; i < 2; i++) {
if (a[i].stipendio > 1200) {
printf("%d %d", a[i].codice, a[i].stipendio);
}
}
return 0;
}
您的代码将输出预期的输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.