在此示例中,您將學習到兩個距離(英寸-英尺),將其相加并在屏幕上顯示結果。
要理解此示例,您應該了解以下C語言編程主題:
12英寸等于1英尺。
#include <stdio.h> struct Distance { int feet; float inch; } d1, d2, result; int main() { printf("輸入第一距離\n"); printf("輸入英尺: "); scanf("%d", &d1.feet); printf("輸入英寸: "); scanf("%f", &d1.inch); printf("\n輸入第二距離\n"); printf("Enter feet: "); scanf("%d", &d2.feet); printf("Enter inch: "); scanf("%f", &d2.inch); result.feet = d1.feet + d2.feet; result.inch = d1.inch + d2.inch; //當英寸大于12時,將其更改為英尺。 while (result.inch > 12.0) { result.inch = result.inch - 12.0; ++result.feet; } printf("\n距離的總和 = %d\'-%.1f\"", result.feet, result.inch); return 0; }
輸出結果
輸入第一距離 輸入英尺: 23 輸入英寸: 8.6 輸入第二距離 輸入英尺: 34 輸入英寸: 2.4 距離的總和 = 57'-11.0"
在此程序中,定義了一個結構Distance。該結構具有兩個成員inch(float)和feet(int)。
創(chuàng)建了兩個變量(d1和d2),其中存儲了兩個距離(inch 和feet)。然后,兩個距離之和存儲在result結構變量中。如果英寸大于12,則將其轉換為英尺。最后,結果打印在屏幕上。