我应该在条件语句中更改什么来生成正确的三角形分类?

时间:2017-12-10 21:36:31

标签: c ubuntu-16.04

我想让用户输入任意三个值来指示三角形边的尺寸。代码中的条件语句将分类边是否构成三角形。如果它确实形成一个三角形,它将显示三角形是否为斜角或右边或两者。

#include <stdio.h>  

int main(void)  
{  
//Declare the variables for the sides of the triangle  
float a; //first side  
float b; //second side  
float c; //third side  
float scalene;  //check for scalene  
float right; //check for right  
float ans; //check if sides are a triangle  
float rep; //check if user wants to continue after the sides are not a 
triangle  

//Get user inputs for the sides of the triangle  
printf("Input the first side of the triangle: ");  
scanf("%f", &a);  

printf("Input the side for the second side of the triangle: ");  
scanf("%f", &b);  

printf("Input the last side of the triangle: ");  
scanf("%f", &c);  

//Conditional statements:  

//Determine if the sides make up a triangle  
>if ((a+b)<c || (b+c)<a || (a+c)<b)  
>{  
ans=0;  
}  
else  
{  
ans=1;  
}  
//If the sides make up a triangle, is the triangle scalene? If scalene, 
//each side is unique to the others  
for (ans=1;ans<3;ans++)  
{  
if (a==b || a==c || b==c)  
{  
scalene=0;  
>}  
else  
{  
scalene=1;  
}  
//if the sides make a right triangle, they would satisfy one of the 
//following Pythagorean theorem  
if ((a*a+b*b)==(c*c) || (b*b+c*c)==(a*a) || (a*a+c*c)==(b*b))  
{  
right=1;  
}  
else  
{  
right=0;  
}  

for (ans=0;ans<2;ans++)  
>{  
printf("Your sides do not make a triangle. Enter 1 if you would like to 
input new values. Enter any other number to finish: \n");  
scanf("%f", &rep);  
}  
if (rep==1)  //repeat the steps again  
{  
printf("Input the first side of the triangle: ");  
scanf("%f", &a);  

printf("Input the side for the second side of the triangle: ");  
scanf("%f", &b);  

printf("Input the last side of the triangle: ");  
scanf("%f", &c);  
>}  
else  
{  
printf("Thank you for using Triangle Check. Have a nice day!");  
return 0;  
}  
}  

//Display the results to the user  
if (scalene==1 && right==1)  
{  
printf("Your triangle is both a scalene and right!");  
return 0;  
}  
else if (scalene==0 && right==1)  
{  
printf("Based on your sides, it is a right triangle!");  
return 0;  
}  
else if (scalene==1 && right==0)  
{  
printf("Based on your sides, it is a right triangle!");  
return 0;  
}  
else  
{  
printf("Your triangle is neither right or scalene.");  
return 0;  
}  


 return 0;  
 }  

如果我为侧面输入3,4,5,我应该得到三角形组成一个直角三角形。

但是我认为双方并不构成三角形。

1 个答案:

答案 0 :(得分:1)

你的逻辑很混乱,因此你很困惑。摆脱ans - 你不需要它。将您的程序构建为立即响应内容。摆脱你不需要的循环。 (这个程序根本不需要任何循环。)

例如,当检查是三角形时,请检查,如果失败,退出

if ((a+b)<c || (b+c)<a || (a+c)<b)
{
  puts( "Alas, your sides to not make a triangle." );
  return 1;
}

可以让用户再次运行程序再试一次。 (是的,你可以这样做,以便再次询问,但这会增加不需要的复杂性。专注于给你的任务。)

如果代码继续经过这个位置,那么你知道它必须是一个三角形。下一个技巧是测试三角形的类型。例如:

if (a != b && b != c)
{
  puts( "The triangle is SCALENE." );
}

继续进行下一次测试。

恶意程序(您的程序使用ansscaleneright等除了报告真值之外什么也不做)请不要帮助您。避免棘手。

祝你好运!