C++三角形程序:未填充时Color输出N/A的实现求助
问题:三角形未填充时Color输出N/A的实现
需求:当用户输入0表示三角形未填充时,程序的Color字段需输出
N/A,当前代码在if (filled == 0)块中不知道如何处理。期望输出示例:
Input the length of three sides of the triangle: 5 5 5 Enter whether the triangle is filled (1) or not (0): 0 Color: N/A Area: 10.8253 Perimeter: 15
当前代码如下:
#include <iostream> #include <math.h> using namespace std; //triangle class toperform all the operation on a triangle class Triangle { double side1, side2, side3; //private variable storing sides of triangle public: bool filled; string color; //default constructor Triangle() { this->side1 = 1.0; this->side2 = 1.0; this->side3 = 1.0; } //constructor two initialize sides of tiangle with the given value Triangle(double one, double two, double three) { this->side1 = one; this->side2 = two; this->side3 = three; } //function to return perimiter of triangle double getPerimeter() { return this->side1 + this->side2 + this->side3; } //function to return area of triangle double getArea() { double p = getPerimeter() / 2; double area = p * (p - this->side1) * (p - this->side2) * (p - this->side3); return sqrt(area); } }; int main() { double a, b, c; int filled; string col = ""; cout << "Input the length of three sides of the triangle: "; cin >> a >> b >> c; Triangle triObj(a, b, c); cout << "Enter whether the triangle is filled (1) or not (0): "; cin >> filled; triObj.filled = filled; if (filled == 1) { cout << "Enter the colour of the triangle: "; cin >> col; triObj.color = col; } if (filled == 0) { //Need help with this } cout << "Color: " << triObj.color; cout << "\nArea: " << triObj.getArea(); cout << "\nPerimeter: " << triObj.getPerimeter() << '\n'; cout << "\nWas the triangle filled?: "; if (triObj.filled) cout << "True\n"; else cout << "False\n"; }
解决方案
有两种简洁的实现方式:
方式一:输出时直接判断填充状态
不需要修改if (filled == 0)块,直接在输出Color的位置添加条件判断,逻辑更清晰:
// 替换原有的cout << "Color: " << triObj.color; cout << "Color: "; if (triObj.filled) { cout << triObj.color; } else { cout << "N/A"; }
方式二:在未填充分支中给color赋值
如果希望triObj.color本身存储N/A,直接在空的if块中赋值即可:
if (filled == 0) { triObj.color = "N/A"; }
修改后的完整main函数(以方式一为例)
int main() { double a, b, c; int filled; string col = ""; cout << "Input the length of three sides of the triangle: "; cin >> a >> b >> c; Triangle triObj(a, b, c); cout << "Enter whether the triangle is filled (1) or not (0): "; cin >> filled; triObj.filled = filled; if (filled == 1) { cout << "Enter the colour of the triangle: "; cin >> col; triObj.color = col; } // 输出Color时判断填充状态 cout << "Color: "; if (triObj.filled) { cout << triObj.color; } else { cout << "N/A"; } cout << "\nArea: " << triObj.getArea(); cout << "\nPerimeter: " << triObj.getPerimeter() << '\n'; cout << "\nWas the triangle filled?: "; if (triObj.filled) cout << "True\n"; else cout << "False\n"; }
内容的提问来源于stack exchange,提问作者user20544996
相关产品推荐
相关产品推荐

