函数中未初始化的局部变量
问题描述:
我试图模块化我以前工作过的程序。我已经把所有的东西都拿出来放到了函数中。我的问题是,当我拥有Main中的所有内容时,它工作良好,无需初始化变量并等待用户输入数字。现在,他们在函数中,我不断收到错误,他们没有初始化。为什么是这样?如果我让他们都0,那么当用户输入他们的人数变量留0。这里是我的代码:函数中未初始化的局部变量
#include <iostream>
#include <cstdlib>
using namespace std;
void displayMenu();
void findSquareArea();
void findCircleArea();
void findTriangleArea();
const double PI = 3.14159;
int main()
{
displayMenu();
return 0;
}
void displayMenu() {
int choice;
do {
cout << "Make a selection for the shape you want to find the area of: \n";
cout << "1. Square\n";
cout << "2. Circle\n";
cout << "3. Right Triangle\n";
cout << "4. Quit\n";
cin >> choice;
switch (choice) {
case 1:
findSquareArea();
break;
case 2:
findCircleArea();
break;
case 3:
findTriangleArea();
break;
case 4:
exit(EXIT_FAILURE);
default:
cout << "Invalid entry, please run program again.";
break;
}
for (int i = 0; i <= 4; i++) {
cout << "\n";
}
} while (choice != 4);
}
void findSquareArea() {
double length,
area = length * length;
cout << "Enter the length of the square.";
cin >> length;
cout << "The area of your square is " << area << endl;
}
void findCircleArea() {
double radius,
area = PI * (radius * radius);
cout << "Enter the radius of the circle.\n";
cin >> radius;
cout << "The area of your circle is " << area << endl;
}
void findTriangleArea() {
double height, base,
area = (.5) * (base) * (height);
cout << "Enter the height of the triangle.\n";
cin >> height;
cout << "Enter the length of the base.\n";
cin >> base;
cout << "The area of your triangle is " << area << endl;
}
答
您有基于未初始化的变量表达式,如area = length * length
in double length, area = length * length
;请注意,C++不像例如Excel,您可以在其中定义一个公式,该公式在参数更改时会自动重新计算。 “公式”在代码被陈述的地方进行评估。
所以你的代码像...
double length,
area = length * length;
cout << "Enter the length of the square.";
cin >> length;
cout << "The area of your square is " << area << endl;
应该这样写......
double length = 0.0, area;
cout << "Enter the length of the square.";
cin >> length;
area = length * length;
cout << "The area of your square is " << area << endl;
+0
这就是我所做的感谢VTT的评论,但我会对此赞不绝口,因为这是第一个正确的答案。 –
'双长度,面积=长*长度;'你初始化之前使用'length' – VTT
所以问题是我在初始化区域长度*长度? –
这是这样的问题的一般模式,你做同样的'基地'和'半径' – VTT