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; }
解决方案
有两个问题。
正如@nm 在评论中指出的那样:
if (a[i].anno=2000)
正在执行一项任务并且总是正确的(因为2000
是正确的)。你想比较。==
使用双倍if (a[i].anno == 2000)
正如@SamiHult 在评论中指出的那样:
n/100
any 将始终为 00 <= n && n < 100
,因为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;
}
您的代码打印预期的输出。
推荐阅读
- wordpress - 每个克隆都有额外选项的 Wordpress Metabox
- angular - *ngFor 添加空格以选择 Angular 形式
- c++ - 如何将一个反向外壳放在一个字符串中并将其打印到终端?
- html - display:none 在 Outlook 中不一致,但在 chrome 中有效
- javascript - 在查询 API 端点之前无法获取地理位置数据
- bash - 如何使用 sed 命令替换文件中两个单引号之间的文本?
- machine-learning - 神经网络 :: 在不知道类总数的情况下进行分类
- reactjs - 如何将函数指定为具有默认值的钩子的可选参数
- python-3.x - Python + Selenium 需要新窗口
- sql - 如何运行将数据作为 nvarchar 传递的过程?