This question already has an answer here:
这个问题已经有了答案:
- Compile error: with request not something structure or union error 2 answers
- 编译错误:请求时不需要任何结构或错误2的答案。
I'm having trouble with my code. My program is a program to simplify fractions. So my problem is this:
我的代码有问题。我的程序是一个简化分数的程序。所以我的问题是:
I declare the structure Fraction. And then I declare structure Fraction f in my main function.
我声明结构分数。然后我在主函数中声明结构f。
But when I try to use any member of the structure fraction (i.e. f.num, f.den) it says it's not a member of a structure or union. I have like 10 errors all saying the same thing for my program.
但是当我尝试使用结构分数的任何成员时(即f。它说它不是一个结构或联盟的成员。我有10个错误,对我的程序说的都是一样的。
The error (verbatim): error: request for member "num" in something not a structure of union
错误(一字不差):错误:请求成员“num”在某种非联合结构中。
#include <stio.h>
struct Fraction{
int num;
int den;
int lownum;//lownum = lowest numerator.
int lowden;//lowden = lowest denominator
int error;
};
void enter(struct Fraction *f);
void simplify(struct Fraction *f);
void display(const struct Fraction *f);
int main(void){
struct Fraction f;
printf("Fraction Simplifier\n");
printf("===================\n");
enter(&f);
simplify(&f);
display(&f);
}
void enter(struct Fraction *f){
printf("Please enter numerator : \n");
scanf("%d", &f.num);
printf("please enter denominator : \n");
scanf("%d", &f.den);
printf("%d %d", f.num, f.den);
}
void simplify(struct Fraction *f){
int a;
int b;
int c;
int negative; //is fraction positive?
a = f.num;
b = f.den;
if (a/b < 0){
negative = 1;
}
if(b == 0){
f.error = 1;
}
if(a < 0){
a = a * -1;
}
if(b < 0){
b = b * -1;
}
//euclids method
if(a < b){
c = a;
a = b;
b = c;
}
while(b != 0){
c = a % b;
a = b;
b = c;
}
f.lownum = f.num / a;
f.lowden = f.den / a;
if(negative = 1){
f.lownum = f.lownum * -1;
}
}
void display (const struct Fraction *f){
if (f.error != 1){
printf("%d / %d", f.lownum, f.lowden);
}else{
printf("error");
}
}
2 个解决方案
#1
7
In
在
void simplify(struct Fraction *f)
f
is a pointer to struct Fraction
. Therefore, instead of
f是struct分数的指针。因此,而不是
a = f.num;
you have to write
你必须写
a = (*f).num;
which can be shortened to the equivalent notation:
可以简化为等价符号:
a = f->num;
The same applies to all other references to struct Fraction *f
in your functions.
这同样适用于函数中struct分数*f的所有其他引用。
#2
0
You use a pointer (struct Fraction *f). So you have to acces members with the -> operator:
使用一个指针(struct分数*f)。所以你必须加入->操作人员:
f->num
#1
7
In
在
void simplify(struct Fraction *f)
f
is a pointer to struct Fraction
. Therefore, instead of
f是struct分数的指针。因此,而不是
a = f.num;
you have to write
你必须写
a = (*f).num;
which can be shortened to the equivalent notation:
可以简化为等价符号:
a = f->num;
The same applies to all other references to struct Fraction *f
in your functions.
这同样适用于函数中struct分数*f的所有其他引用。
#2
0
You use a pointer (struct Fraction *f). So you have to acces members with the -> operator:
使用一个指针(struct分数*f)。所以你必须加入->操作人员:
f->num