簡體   English   中英

在函數中使用結構體數組?

[英]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; }

有兩個問題。

  1. 正如@nm在注釋中指出的: if (a[i].anno=2000)正在執行賦值並且始終為true(因為2000為true)。 您要比較。 if (a[i].anno == 2000)if (a[i].anno == 2000)使用double ==

  2. 正如@SamiHult在注釋中指出的:對於任何0 <= n && n < 100n/100始終為0,因為nint 使用doublefloat可以進行浮點運算。 或如@alk所指出的,您可以先相乘然后相除,這樣就可以保持整數數學(a[i].stipendio * n) / 100

  3. 這是很好的代碼,但是縮進只是很痛。

修復這些錯誤后:

#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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM