变量范围和传递全局变量

时间:2014-10-22 16:21:10

标签: c++ global-variables scope

我必须编写一个程序来计算给定容差的e值。我必须有一个单独的文件用于计算e的函数,我必须只使用全局变量。我不能从我的功能中传回任何东西。我每次都得到相同的输出答案,我不认为我使用全局变量或调用我的函数吗?提前抱歉这里代码可能格式不正确。

#include<iomanip>
#include<iostream>
#include<cmath>
#include<string>

using namespace std;

void find_e();
double tol = 0;
double e;
double euler = 2.718281828459045;
double diff;
string ans = "yes";


int main()
{
  while(ans == "yes")
{


cout<<"This program will estimate the value of Euler's number to your desired tolerance"<<endl<<endl;
cout<<"Please input your tolerance: ";
cin>>tol;
system("cls");

if(tol > 0.0)
{

        find_e();

        cout<<"The new value of e is "<<fixed<<setw(12)<<setprecision(10)<<e<<endl;
        cout<<"The actual value of e is "<<fixed<<setw(12)<<setprecision(10)<<euler<<endl;
        cout<<"The difference is "<<fixed<<setw(12)<<setprecision(10)<<diff<<endl;
}

else
{
    cout<<"You can't have a negative tolerance"<<endl<<endl;
}

cout<<"Would you like to run this again? yes for yes, any other key for no\n\n";
cin>>ans;
}
system("pause");

return 0;
} 

这是我在单独文件中的功能:

#include<iomanip>
#include<iostream>
#include<cmath>
#include<string>
using namespace std;


extern double e;
double newe;
extern double diff;
int n = 1;
extern double tol;

void find_e()

{

do
    {

        e = (n,(1+(1/n)));

        diff = abs(newe - e);

        newe = e;
        n++;



    }
    while(diff>tol);




return;
} 

0 个答案:

没有答案