⑴ 編程題:編寫程序輸入三角形的3條邊長,計算並輸出三角形的面積。
一、程序分析
三角形面積海倫公式:√[ p ( p - a ) ( p - b ) ( p - c ) ] 。其中 p = (a + b + c) / 2 。a、b、c分別是三角形的三邊長。
二、根據三角形面積計算公式用if語句編寫程序如下:
#include "stdio.h"
#include "math.h"
int main(void)
{
float a = 0, b = 0, c = 0, p = 0;
float area = 0;
printf("Please input three sides of triangle:");
scanf_s("%f %f %f", &a, &b, &c);
if((a + b) > c && (a + c) > b && (b + c) > a)
{
p = (a + b + c) / 2;
area = sqrt(p * (p - a) * (p - b) * (p - c));
}
else
printf("Triangle does not exist! ");
printf("The area of triangle is:%f ", area);
return 0;
(1)三角邊長演算法軟體擴展閱讀:
還可以使用switch語句計算三角形的面積,編寫程序如下
#include "stdio.h"
#include "math.h"
int main(void)
{
float a = 0, b = 0, c = 0;
float p = 0;
printf("Please input three sides of triangle:");
scanf_s("%f %f %f", &a, &b, &c);
switch (a + b > c && a + c > b && b + c > a)
{
case 0:printf("Triangle does not exist! "); break;
case 1:
p = (a + b + c)*0.5;
printf("The area of triangle is:%f ", sqrt(p * (p - a) * (p - b) * (p - c)));
break;
}
return 0;
}