问:如何使用开关通过角度知道三角形是否有效
Q: How to know whether the triangle is valid or not by angles using switch?
我想使用开关,我不能!!
#include <iostream>
using namespace std;
int main() {
char op ;
float x, y, z;
cout << "Enter the three angles : n ";
cin >> x >> y >> z;
switch (op){
case '+' :
cout << x + y + z == 180;
break;
default:
cout << "A triangle is Not valid !! n ";
}
system("pause");
}
您可以使用
switch
来替代if
,如下所示:
#include <math.h>
switch(static_cast<int>(round(x + y + z))) {
case 180:
cout << "The triangle is validn";
break;
default:
cout << "The triangle is not validn";
break;
}
我使用round()
来缓解浮点数学是近似的问题。
如果作业是根据结果进行切换,Baramr 的方法就是你想要的。
为了完整起见:如果作业是根据 op 进行切换以学习跌倒,您可能会在条件中使用中断并跌入默认值,或者如果您有多个操作,请转到标签。
失败和显式跳转都被认为是不好的做法,但是当你学习 switch 时,你应该知道它们至少存在以调试它们。
switch (op){
case '+' :
if( (static_cast<int>(round(x + y + z))) == 180 ){
cout << "The triangle is validn";
break;
}
default:
cout << "A triangle is Not valid !! n ";
}
奖励验证:检查角度值是否为负值。
#include <iostream>
#include <cmath>
using namespace std;
int main() {
float x, y, z;
cout << "Enter the three angles : n ";
cin >> x >> y >> z;
if (x <= 0 || y <= 0 || z <= 0) {
cout << "Invalid angles" << endl;
system("pause");
return 0;
}
switch (static_cast<int>(round(x + y + z))){
case 180:
cout << "Valid triangle" << endl;;
break;
default:
cout << "A triangle is Not valid !! n ";
}
system("pause");
}
相关文章:
- 欧拉项目#8答案是大以获得有效答案
- 调整大小后指向元素值的指针unordered_map有效?
- 为什么是0;C++中的有效语句
- 最高有效数字侧的第N位
- GCC对可能有效的代码抛出init list生存期警告
- 有效地使用std::unordered_map来插入或增加键的值
- 绘制旋转的三角形
- c++中O(n^(1/3))中一个数的除数的有效计数
- 使用无符号字符数组有效存储内存
- 自定义先决条件对移动分配运算符有效吗
- 如何用for循环在c++中生成单词三角形
- 如何使用递归打印修改后的星号三角形图案
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 有哪些有效的方法可以消除一组 100 万个字符串>重复数据?
- C++ 创建带有 for 循环的三角形
- 为什么这种直接初始化有效?(C++17)
- 递归函数有效,但无法记忆
- 问:如何使用开关通过角度知道三角形是否有效
- 如何知道三角形是否有效
- 使用GL_TRIANGLE_STRIP或索引gl_三角形来绘制动态数量的四边形是否更有效?