作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我不明白如何使用枚举类型。我明白它们是什么,但我不太明白它们的目的。
我编写了一个程序,输入三角形的三个边并输出它们是等腰、不等边还是等边。我想在某处合并枚举类型,但不知道在哪里以及如何使用它们。任何帮助将不胜感激。
#include <iostream>
using namespace std;
enum triangleType {scalene, isosceles, equilateral, noTriangle};
triangleType triangleShape(double x, double y, double z);
void printTriangleShape(triangleType shape);
int main()
{
double x, y, z;
triangleType scalene, isosceles, equilateral, noTriangle;
cout << "Please enter the three sides of a triangle:" << endl;
cout << "Enter side 1: ";
cin >> x;
cout << endl;
cout << "Enter side 2: ";
cin >> y;
cout << endl;
cout << "Enter side 3: ";
cin >> z;
cout << endl;
triangleType t = triangleShape(x, y, z);
printTriangleShape(t);
return 0;
}
triangleType triangleShape(double x, double y, double z)
{
triangleType scalene, isoceles, equilateral, noTriangle;
if (((x+y) > z) && ((x+z) > y) && ((y+z) > x))
{
cout << "You have a triangle!" << endl;
if (x == y && y == z)
return equilateral;
else if (x == y || x == z || y == z)
return isosceles;
else
return scalene;
}
else if ((x+y) <= z || ((x+z) <= y) || ((y+z) <= x))
return noTriangle;
}
void printTriangleShape(triangleType shape)
{
switch (shape)
{
case scalene: cout << "Your triangle is Scalene!" << endl;
break;
case isosceles: cout << "Your triangle is an isosceles!" << endl;
break;
case equilateral: cout << "Your triangle is an equilateral!" << endl;
break;
}
}
最佳答案
这是一个值,您可能希望从函数中返回它。
尝试:
triangleType triangleShape(double x, double y, double z) {
if (...) {
return scalene;
} else if (...) {
return isosceles.
} else if (...) {
return equilateral
} else {
return noTriangle;
}
}
请注意,您可以打印结果,但它会打印为整数: 斜角 = 0,等腰 = 1,...
编辑,对于打印你可能想这样做:
void printTriangleShape(triangleType shape) {
switch (shape) {
case scalene:
cout << "Your triangle is Scalene!" << endl;
break;
case isosceles:
cout << "Your triangle is isosceles!" << endl;
break;
...;
}
}
关于c++ - 如何在 C++ 中使用枚举类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2602874/
我是一名优秀的程序员,十分优秀!