S.E.M.F。物理C++代码

S.E.M.F. physics C++ code

需要一些帮助来解决此程序的一个小问题。我创建了 S.E.M.F。在物理学中,C++ 计算公式一切都很好,但我的 B.E。公式中有 a5。

它说错误:标识符 "a5" 未定义,我知道这是什么意思,但是如果我为我的输入 even even 或 even odd 或 odd odd,我如何从选择语句中获取 a5 Z 值。

#include <iostream>
#include <cstdlib>
#include <math.h>

using namespace std;

int main()
{
    int A, Z;

    // Main body of Semi-Empirical Mass Formula
    cout <<"Enter the mass number A: ";
    cin >> A;
    cout <<"\n";
    cout <<"Enter the atomic number Z: ";
    cin >> Z;
    cout <<"\n";

    // Constants from formula, units in MeV(millions of electron volts)
    double a1 = 15.67;          
    double a2 = 17.23;
    double a3 = 0.75;
    double a4 = 93.2;

    if(Z % 2 == 0 && (A - Z) % 2 == 0)

        double a5 = 12.0;

    else if(Z % 2 != 0 && (A - Z) % 2 != 0)

        double a5 = -12.0;

    else

        double a5 = 0;


    // Formula for to compute the binding energy
    double B =a1 * A - a2 * pow( A, 2/3) - a3 * (pow(Z, 2) / pow(A, 1/3)) - a4 * (pow(A - 2 * Z, 2) / A) + (a5 / pow(A, 1/2));

    // Formula for to compute the binding energy per nucleon
    double B_E = B / A;


    return 0;

}

您需要在 if 语句之外声明 a5,然后在 if 语句中设置它

double a5 = 0;

if(Z % 2 == 0 && (A - Z) % 2 == 0)
    a5 = 12.0;
else if(Z % 2 != 0 && (A - Z) % 2 != 0)
    a5 = -12.0;

正如您现在拥有的那样,变量 a5 将仅存在于声明它的 if 语句中。

a5 由于范围问题未定义。

因为您在 if -- else 语句的子句中声明 a5,所以该声明仅在声明它的语句内具有作用域。

要解决此问题,请在其范围扩展到您使用 a5 的后续语句的位置声明 a5:

double a1 = 15.67;          
double a2 = 17.23;
double a3 = 0.75;
double a4 = 93.2;
double a5 = 0.0;
//^ declare a5 here, it will be in scope when used in subsequent statements past the else clause


if(Z % 2 == 0 && (A - Z) % 2 == 0)

    a5 = 12.0;

else if(Z % 2 != 0 && (A - Z) % 2 != 0)

    a5 = -12.0;


// Formula for to compute the binding energy
double B =a1 * A - a2 * pow( A, 2/3) - a3 * (pow(Z, 2) / pow(A, 1/3)) - a4 * (pow(A - 2 * Z, 2) / A) + (a5 / pow(A, 1/2));

只需将 a5 的声明向上移动一点:

double a5;
if(Z % 2 == 0 && (A - Z) % 2 == 0)
    a5 = 12.0;
else if(Z % 2 != 0 && (A - Z) % 2 != 0)
    a5 = -12.0;
else
    a5 = 0;

放入

的定义
double a5 = 0.0;

就在 a4 定义的下方,并在每个 ifs 案例中使用它。