area always becomes 0-structures
i hav开发者_运维知识库e made a program to find the area of a rectangle but it always gives area 0.Dont get why.
#include<stdio.h>
#include<conio.h>
struct rectangle
{
float width;
float length;
}rect;
void rectangleget(void);
void rectangleset(void);
void area( void);
void perimeter(void);
void main(void)
{
clrscr();
rectangleset();
rectangleget();
area();
perimeter();
getch();
}
void rectangleset(void)
{
for(;;)
{
printf("enter length:");
scanf("%f",&rect.length);
if(!(rect.length>0 &&rect.length<=20.00))
{
printf("invalid entry");
}
else
{
break;
}
}
}
void rectangleget(void)
{
char ch;
for(;;)
{
printf("enter width:");
scanf("%f",&rect.length);
if(!(rect.length>0 &&rect.length<=20.00))
{
printf("invalid entry Try again\n");
}
else
{
break;
}
}
}
void area(void)
{
float areaa=1;
areaa=rect.length*rect.width;
printf("area is %f",areaa);
}
void perimeter(void)
{
float peri=0;
peri=2*(rect.length+rect.width);
printf("perimeter is %f",peri);
}
After calling scanf, you always set rect.length. Seems like a classic case of cut&paste bug. Which is also an indication that your code needs some refactoring. (In fact, your code is quite horrible).
Both functions, rectangleget()
and rectangleset()
are initializing the length
member of the struct - width
never gets initialized.
These functions seem oddly named - maybe they should be named setlength()
and setwidth()
(and set the corresponding member)?
As mentioned in other answers, there are other changes that would make the code better, such as having the initialization functions take a pointer to the structure to initialize. Actually, the rect
to operate on should be a parameter to pretty much any function that's acting on it. But those kinds of changes may be topics for later exercises...
For example, you might have functions with the following signatures:
void rectangle_set_width( struct rectangle*);
void rectangle_set_length( struct rectangle*);
float rectangle_area( struct rectangle const*);
float rectangle_perimeter( struct rectangle const*);
So that they can operate on any rectangle
variable, not just the single global variable.
Because you are not setting rect.width
, which happens to be somehow initialized to zero.
You're never setting rect.width
. A rectangle of 0 width has an area of 0, now matter how long it is.
You have an obvious error in rectangleget()
.
Do you know how to use a debugger yet? It would help you a lot to set breakpoints and watch the course of the program to follow what values your variables are getting set to. I'll leave it to you figure out where the error is since it is homework.
精彩评论