2010-01-27 108 views
0

我正在处理一个小问题,并花了好几个小时试图弄清楚我做错了什么。使用Dev ++编译器,它有时会有一些神秘的错误信息。关于函数和错误检查的新手C++问题

我试图让体积计算功能,并得到它的工作,但我有2个小尼特。我解决这个问题后,将工作在错误检查。

  1. 随着函数的增加,出于某种原因现在使用dev ++,程序不会暂停(按任意键继续)。

  2. 卷是空白而不是数字。

感谢 PC

// The purpose of this program is to determine the Volume of a 
// square-based pyramid after the user inputs the Area and 
// the Height. 
#include <iostream> 
#include <iomanip> 
using namespace std; 
double calcvolume(double a, double h) 
{ 
    double volume; 
    volume = (a * h)/3; 
    return (volume); 

} 

int main() 
{         
    double area, height, volume;     // declare variables 

    cout << "Please enter the Area of the Square-based pyramid:";  // requests users input 
    cin >> area;              // assigns user input to area 

    cout << "Please enter the Height of the Square-based pyramid:";  // requests user input 
    cin >> height;  
                // assigns user input to height 
    cout << "Area= " << area << "\n";         // Prints user input for area 
    cout << "Height= " << height << "\n"; 
    calcvolume(area,height);  

    cout << "Volume= " << fixed << showpoint << setprecision(2) << volume << "\n"; // Prints resolution to the formula stored in volume 

    system("pause"); // forces DOS window to pause to allow user to utilize program 
    return 0; 
} 
+2

如果您在编写函数进行计算时需要帮助,请发布您已经提出的内容,我们将从此处为您提供帮助。 – luke 2010-01-27 18:59:47

+1

我们希望看到你写的内容无效 - 我们无法修复工作代码。 – 2010-01-27 19:01:13

+1

如果你需要帮助来弄清楚为什么事情不起作用,那么显示什么是有效的,而不是没有用的。 – 2010-01-27 19:01:57

回答

1

你更新的代码看起来是正确的,但你是不是存储calcvolume返回值。您在calcvolume中声明的音量变量与您在main中声明的音量变量不同。这些变量中的每一个只能从它在声明的函数内引用。

为了节省体积,

calcvolume(area,height);

应该

volume = calcvolume(area,height);

这将在主函数中存储从calcvolume返回的值在volume变量中。

+0

有趣。我认为音量将通过该功能设置并返回。那么我会.. 谢谢 PC – 2010-01-27 23:17:32

+0

你可以通过声明'calcvolume'的参数为引用来获得这样的行为。我建议你花更多的时间来研究C++编程的教程和指南,但它是一种可以独自使用的语言。 – Eric 2010-01-28 02:40:34

0

你要结果分配的calcvolume(area,height)主的volume如下:

volume = calcvolume(area,height); 

现在你可以放心地使用主音量变量。

我猜你的程序甚至没有达到system("pause")行,并且崩溃了上面的行。这可能是因为volume从来没有设置任何东西,并持有垃圾数据。这个垃圾数据使cout << ...失败。

之前您解决calcvolume(area,height)线,尝试修复您的变量声明,以使您的变量初始化为零:

double area=0.0, height=0.0, volume=0.0; // declare variables 

现在再次运行它,看看它是否输出Volume=0.00和暂停。

将变量初始化为零或有意义的东西总是好的。否则,它们将被初始化为随机数据(无论这些数据是否已存在于这些内存字节中),并且会使故障排除变得更加困难。