2014-03-19 39 views
0

函數double computeArea(Rectangle *r)使用給定的兩點座標,topLeftbotRight計算矩形的面積。我有點困惑,爲什麼我的r沒有進入main函數的功能。用於計算給定兩點矩形區域的嵌套結構(C語言)

這裏就是我所做的:

#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 
+1

你得到的實際輸出是什麼? – Inox

回答

2

%d是打印整數。您可以使用%f打印雙打:

printf("Area = %f", computeArea(&r)); 
+0

謝謝邁克。忘了浮動的自動提升,不需要渲染'l'(因爲所有的浮動都會被提升爲雙倍)。 –

0

兩點你:

1)您在這裏使用了錯誤的格式字符串:

printf("Area = %d", computeArea(&r)); 

%d是整數,%f應用於印刷浮標。事實上,你看到0作爲返回結果只是運氣的平局。傳遞的數據類型與預期的printf不同會導致未定義的行爲,因此可能會發生任何事情。

2)你會得到錯誤的值的區域,因爲你允許負值。您需要取絕對值heightwidth以獲得正確的區域。