计算给定两点矩形面积的嵌套结构(C语言)
函数计算给定两点矩形面积的嵌套结构(C语言),c,function,pointers,structure,C,Function,Pointers,Structure,函数double computeArea(矩形*r)使用给定的两点坐标计算矩形的面积,topLeft和botRight。我有点困惑,为什么我的r没有从main函数传递到函数中 以下是我所做的: #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> #include <math.h> typedef struct { double x; double
double computeArea(矩形*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 = 0
%d
用于打印整数。您可以使用%f
打印双精度:
printf("Area = %f", computeArea(&r));
对你来说有两点:
1) 您在此处使用了错误的格式字符串:
printf("Area = %d", computeArea(&r));
%d
表示整数,%f
应用于打印浮点数。您将0
视为返回结果的事实只是抽签的运气。传递与预期的printf
不同的数据类型会导致未定义的行为,因此那里可能发生任何事情
2) 您将获得错误的面积值,因为您允许负值。您需要取
高度
和宽度
的绝对值才能得到正确的面积。您得到的实际输出是什么?谢谢Mike。忘记了自动将float升级为double,从而不需要l
(因为所有float都将升级为double)。
printf("Area = %d", computeArea(&r));