我是C ++的新手。我参加了Python课程,但宁愿继续学习更有用的语言。但我正在用C ++重做那个课程中的几个作业,以帮助我顺利完成。
这个特殊的问题是编写能够解决Lorentz因子的代码,输入光速(速度/ c)的一小部分应该在0和1之间。我确信这是一件非常简单的事情我做错了;来自Python的我可能不熟悉的东西。但帮助将不胜感激。我一直得到答案" nan"。它与我的类型声明有关吗?根据我的理解,由于我使用小数,我应该使用浮动吗?
这里是Lorentz等式(但请记住,我的代码接受v / c作为一个数字):
#include <iostream>
#include <math.h>
using namespace std;
float lorentz_factor (float v) {
float answer = 1 / sqrt(1 - exp(v));
return answer;
}
int main() {
float v;
cout<<"Please enter a number between 0 and 1";
cin>> v;
while (!((v < 1) && (v > 0))) { // "v" should be entered as a fraction of the speed of light.
cout<<"Try again: ";
cin>>v; // and only accepted if it is between 0 and 1
}
float factor = v;
cin.ignore();
cout<<"The lorentz_factor is: "<< lorentz_factor (factor) << "\n";
cin.get();
}
帮助我。
答案 0 :(得分:7)
你有:
1 / sqrt(1 - exp(v))
但洛伦兹因素是:
1 / sqrt(1 - v*v)