我参加了C ++课程的介绍,我们正在使用visual studio。我们的任务是创建一个程序,通过键入相应的字符来计算用户可以选择的不同内容。该活动向我们展示了如何在我们的代码中使用函数。我已经设置了第一个计算,但是每次运行它都会出现运行时错误#3,当我在main中初始化circleArea时,circleArea会打印为我初始化它而不是areaCircle函数返回的值。谢谢你把我赶出去,如果这对我很重要,我很抱歉。
/// Lab6Marcelino.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
double pi = 3.14;
// Protoypes
void showMenu(char & c);
void getRadius(double & r, bool &nega);
bool isNegative(double val);
double areaCircle(double &r);
// Main
int _tmain(int argc, _TCHAR* argv[])
{
char menuChoice;
double radius;
bool negative = true;
double circleArea;
showMenu(menuChoice);
if (menuChoice = 'c')
{
getRadius(radius, negative);
areaCircle(radius);
cout << "The radius is " << radius << endl
<< "The area of the circle is: " << circleArea << endl;
}
system("Pause");
return 0;
}
//*************
// FUNCTIONS***
//*************
// Definition of function showMenu
// Shows Menu and asks for user choice.
void showMenu(char &menuChoice)
{
cout << "Enter C or c for the area of a Circle" << endl
<< "Enter T or t for the area of a Triangle" << endl
<< "Enter S or s for the area of a Sphere" << endl
<< "Enter P or p for the area of a triangular Prism" << endl
<< "Enter A or a for information about the author" << endl
<< "Enter Q or q to quit this program" << endl;
cin >> menuChoice;
}
// Definition of function getRadius
// Gets radius from user
void getRadius(double &r, bool &nega)
{
cout << "Enter the radius: ";
cin >> r;
isNegative(r);
while (isNegative(r) == true)
{
cout << "Enter the radius: ";
cin >> r;
isNegative(r);
}
}
bool isNegative(double val)
{
if (val < 0)
return true;
if (val > 0)
return false;
else
{
cout << "Invalid input" << endl;
return true;
}
}
double areaCircle(double &r)
{
double circleArea;
circleArea = pi * r * r;
return circleArea;
}
答案 0 :(得分:2)
areaCircle(radius);
会返回一个值,但您不会将其分配给任何内容。然后,当您尝试将circleArea
与cout一起使用时,它尚未初始化,因此您可能会遇到运行时错误。