c - 在函数中使用结构数组?

标签 c

我正在尝试编写一个函数来更改结构体数组中元素的一个值,但它不起作用,该函数不执行任何操作。我做错了什么?

输入:

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. 作为@n.m。评论中指出:if (a[i].anno=2000)正在执行分配并且始终为 true(因为 2000 为 true)。你想比较一下。使用双 ==为了它if (a[i].anno == 2000)

  2. 正如@SamiHult 在评论中指出的那样:n/100对于任何 0 <= n && n < 100 都将始终为 0 ,因为nint 。使用doublefloat进行 float 学运算。或者正如@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; 
}

您的代码打印预期的输出。

关于c - 在函数中使用结构数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53469649/

相关文章:

c - += 工作不正常?

c# - 使用c#加密数据并使用openssl api解密数据,为什么解密数据末尾有很多垃圾填充?

c - 了解取消引用未初始化指针的 C 的未优化 asm,导致段错误

c++ - 共享内存执行得这么快?

c - 为什么我们像这样在微 Controller 编程中寻址寄存器

c - 函数原型(prototype)中的函数声明(需要帮助)

c - C中的点分十进制转二进制

c - 指向 C 中重新分配的内存块的多个指针

c - 在 C 中使用 UDP 发送数据包并测量耗时

c - 这段代码是如何工作的——关于 c 中的 union 初始化?