函数double computeArea(Rectangle *r)
使用给定的两个点坐标topLeft
和botRight
计算矩形的面积。我有点困惑为什么我的r
没有从main
函数传入函数。
这就是我的所作所为:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <math.h>
typedef struct {
double x;
double y;
} Point;
typedef struct {
Point topLeft; /* top left point of rectangle */
Point botRight; /* bottom right point of rectangle */
} Rectangle;
double computeArea(Rectangle *r);
int main()
{
Point p;
Rectangle r;
printf("\nEnter top left point: ");
scanf("%lf", &r.topLeft.x);
scanf("%lf", &r.topLeft.y);
printf("Enter bottom right point: ");
scanf("%lf", &r.botRight.x);
scanf("%lf", &r.botRight.y);
printf("Top left x = %lf y = %lf\n", r.topLeft.x, r.topLeft.y);
printf("Bottom right x = %lf y = %lf\n", r.botRight.x, r.botRight.y);
printf("Area = %d", computeArea(&r));
return 0;
}
double computeArea(Rectangle *r)
{
double height, width, area;
height = ((r->topLeft.y) - (r->botRight.y));
width = ((r->topLeft.x) - (r->botRight.x));
area = height*width;
return (area);
}
预期产出:
Enter top left point: 1 1
Enter bottom right point: 2 -1
Top left x = 1.000000 y = 1.000000
Bottom right x = 2.000000 y = -1.000000
Area = 2.000000
输出我得到了:
Enter top left point: 1 1
Enter bottom right point: 2 -1
Top left x = 1.000000 y = 1.000000
Bottom right x = 2.000000 y = -1.000000
Area = 0
答案 0 :(得分:2)
%d
用于打印整数。您可以使用%f
打印双打:
printf("Area = %f", computeArea(&r));
答案 1 :(得分:0)
给你两点:
1)您在此处使用了错误的格式字符串:
printf("Area = %d", computeArea(&r));
%d
用于整数,%f
应该用于打印浮点数。您将0
视为返回结果的事实只是抽奖的运气。传递与预期printf
不同的数据类型会导致未定义的行为,因此可能发生任何事情。
2)您将获得错误的区域值,因为您正在允许负值。您需要获取height
和width
的绝对值才能获得正确的区域。