gpt4 book ai didi

c++ - 简单函数的问题

转载 作者:行者123 更新时间:2023-11-28 00:11:13 26 4
gpt4 key购买 nike

我正在编写代码来调用与力、质量和加速度方程有关的函数。函数被正确调用,但输入未按应有的方式相乘。我对第一个函数的输出是一个非常小的数字,第一个函数的输出始终为 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com