我编写了一个程序,它接受两个输入 - 汽车的面积和摩擦系数 - 作为参数,然后计算阻力。
如果用户输入无效的摩擦值(必须为0.2 <= friction <= 0.5
),else
条件才能正常工作。
然而,当我为摩擦输入有效值时,它会进入一个无限循环,从不给我任何错误。
这是我的代码。
double area, friction;
cout << "lutfen surtunen yuzeyi giriniz: \n";
cin >> area;
cout << "lutfen surtunme katsayisini giriniz: \n";
cin >> friction;
calc_force(velocity, area, friction);
// My function
void calc_force(int velocity, double area, double friction)
{
double force;
double seccade = friction;
if(0.2 <= seccade && seccade <= 0.5 ) { // if statement does not work
force = (0.0615)*area*friction*velocity*velocity;
cout << "Velocity\t\t Drag Coefficien\t\t Area\t\t Force\n";
cout << "\t\t" << velocity << "\t\t" << seccade << "\t\t" << area << "\t\t" << force << "\n";
velocity+=5;
if(velocity>40) return ;
cout << "lutfen surtunme katsayisini giriniz: \n";
cin >> friction;
cout << "lutfen surtunen yuzeyi giriniz: \n";
cin >> area;
calc_force(velocity, area, friction);
} else { // this works
cout << "lutfen surtunme katsayisini dogru giriniz: \n";
cin >> friction;
cout << "lutfen surtunen yuzeyi giriniz: \n";
cin >> area;
calc_force(velocity, area, friction);
}
}
velocity
被定义为const int
。当我调用并定义函数时,我都有int friction
到double friction
。我已经更正了其他数据类型,如下所示。我使函数递归,因为我希望它重复。
答案 0 :(得分:1)
试试这个:
void calc_force(int velocity, double area, double friction){
double force;
double seccade = friction;
if(0.2 <= seccade && seccade <= 0.5 ){ // if statement does not work
force = (0.0615)*area*friction*velocity*velocity;
cout<<"Velocity\t\t Drag Coefficien\t\t Area\t\t Force\n";
cout<<"\t\t"<<velocity<<"\t\t"<<seccade<<"\t\t"<<area<<"\t\t"<<force<<"\n";
velocity+=5;
}
if (velocity > 40 ) {
return;
} else {
cout<<"lutfen surtunme katsayisini giriniz: \n";
cin>>friction;
cout<<"lutfen surtunen yuzeyi giriniz: \n";
cin>>area;
calc_force(velocity, area, friction);
}
}
这既包含了参数的更改,也将递归移到了if语句之外。这样可以确保可以访问基本案例,并且应该为您提供所需的功能。