我正在编写代码来调用与力,质量和加速度方程有关的函数。这些函数被正确调用,但是输入未按应有的相乘。我对第一个函数的输出是一个疯狂的小数字,并且对第一个函数的输出始终为0。
这是我的代码。任何反馈都将非常有帮助。谢谢。
#include <iostream>
#include <cstdlib>
using namespace std;
void displayMenu();
double force(double);
double secondForce(double,double);
int main(int argc, char** argv)
{
int menuOption;
displayMenu();
system("PAUSE");
return 0;
}
void displayMenu(void)
{
int menuOption;
double weight, accel;
cout << " Main Menu" << endl;
cout << "Enter 1 for Force calculation with acceleration = 9.8m/s^2.\n";
cout << "Enter 2 for Force calculation with user defined acceleration.\n";
cout << "Enter 3 to quit the program.\n";
cin >> menuOption;
if(menuOption==1)
{
cout << "Enter a mass.\n";
cin >> weight;
cout << "The force is ";
cout << force(weight);
cout << "N.";
}
else if(menuOption==2){
cout << "Enter a mass.\n";
cin >> weight;
cout << "Enter an acceleration.\n";
cin >> accel;
cout << "The force is ";
cout << secondForce(weight, accel);
cout << "N.";
}
}
double force(double weight)
{
double force, mass;
force=(mass*(9.8));
return force;
}
double secondForce(double secondMass, double secondWeight)
{
double secondForce, mass, acceleration;
secondForce=(mass*acceleration);
return secondForce;
}
最佳答案
您正在函数中使用未初始化的变量。在程序中使用这些未初始化的变量是undefined behavior。
force=(mass*(9.8)); << mass has a garbage value
secondForce=(mass*acceleration); << mass and acceleration have a garbage value
我想你打算
double force(double weight)
{
return weight * 9.8;
}
double secondForce(double secondMass, double secondAccel)
{
return secondMAss * secondAccel;
}
关于c++ - 麻烦简单的功能,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33021194/