这是我的第一次C++编程实践。当我运行这个程序时,它会显示“输入边长”和“您在计算哪个图形的面积?”。我输入3和平方,但我能得到的唯一结果是"Unknown figure。再试一次。“我不知道为什么会这样。也许有些东西联系不好..。
#include <iostream>
#include<math.h>
using namespace std;
int main() {
int Side;
float Area;
float sqrt2 = 1.414;
float sqrt3 = 1.732;
float sqrt4 = 2;
float sqrt5 = 2.236;
float cot = 2.077;
float pi = 3.141;
char figure;
char equaliteral_triangle,square,pentagon,hexagon,heptagon,octagon;
cout << "Enter the length of the side: " << endl;
cin >> Side;
cout << "Which figure's area are you calculating? " << endl;
cin >> figure;
if(figure == equaliteral_triangle) {
Area = (sqrt3/4) * (Side * Side);
cout << "The area of triangle is, "<< Area << endl;
}
else if (figure == square) {
Area = (Side * Side);
cout << "The area of square is, "<< Area << endl;
}
else if (figure == pentagon) {
Area = (0.25 *(5 *(5 +(2*sqrt5)))) * (Side * Side);
cout << "The area of pentagon is, "<< Area << endl;
}
else if (figure == hexagon) {
Area = ((3*sqrt3)/2) * (Side * Side);
cout << "The area of hexagon is, "<< Area << endl;
}
else if (figure == heptagon) {
Area = (7/4) * (Side * Side) * cot;
cout << "The area of heptagon is, "<< Area << endl;
}
if (figure == octagon) {
Area = (2 * (1+ sqrt2)) * (Side * Side);
cout << "The area of octagon is, "<< Area << endl;
}
else {
cout << "Unknown figure. Try again." << endl;
}
}发布于 2018-02-01 18:04:06
char equaliteral_triangle,square,五边形,六边形,七角形,八角形;你已经声明了这些变量,但还没有初始化它们--它应该是char等量三角形=‘t’,square='s',五角大楼=‘p’,六边形=‘h’,heptagon='H',=‘o’;
发布于 2018-02-01 19:06:34
您需要为您定义的char变量提供一些值。如果不给予他们一些价值,他们将保持未定义,因此你将不匹配他们。请注意,这些
char figure;
char equaliteral_triangle,square,pentagon,hexagon,heptagon,octagon;是变量。如果在控制台中键入square,它将与square变量的值不匹配。所以,首先,与这样的角色合作:
char figure;
char equaliteral_triangle = '3',square = '4',pentagon = '5',hexagon = '6',heptagon = '7',octagon = '8';当您成功并且程序工作时,重构它,以便它将使用switch-case而不是if-else if,在本例中,当您有字符时,if-else if更优雅。
发布于 2018-02-01 17:44:53
您的字符中没有值,这意味着它们都是空值,当您将它们与输入的值用户进行比较时,它们将不相等。
我建议,只有当你只想得到这些数字时,才建议使用边数。
如果你有三个边,你知道它是一个三角形,所以相应地使用公式。
https://stackoverflow.com/questions/48568702
复制相似问题