函数中未初始化的局部变量

时间:2017-10-08 20:19:32

标签: c++

我正在尝试模块化我以前工作过的程序。我把所有东西都从主要的东西中取出并放入功能中。我的问题是,当我在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;

}

1 个答案:

答案 0 :(得分:1)

您的表达式基于未初始化的变量,例如area = length * length中的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;
相关问题