简体   繁体   中英

Can't return value from function?

I wrote this code and there is a problem that I can't seem to work out. The function is supposed to return T1 and cout it from the main but it always gives me an error "T1 is undeclared identifier". Why?

#include<iostream>
#include<math.h>
#include<time.h>
using namespace std;
double factorial()
{
   int i;
   double T1,total=0;
   for(i=0;i<200;i++) 
   {
      clock_t start = clock();

      int a,N,f;
  N=99999;
      f=N;
  for(a=N-1;a>0;a--)
  {
         f=f*a;
      }

      clock_t end = clock();
      T1=double(end-start)/(double) CLOCKS_PER_SEC;
      total=total+T1;
   }
   T1=total/200;
   return T1;
}
int main()
{
   factorial();
   cout<<T1<<endl;

   return 0;
}

Each function only knows it local variables (and globals, which you don't have any defined). You have to create a variable for the result from in main:

int main()
{
   double answer = factorial();
   cout << answer << endl;

   return 0;
}

I don't know if you care, but the factorial value is going to overflow.

Because T1 is not defined under the main() scope, it is only defined under the scope of your function factorial .

You should do this instead:

cout<<factorial()<<endl;

or define T1 like this within your main function:

double T1 = factorial();
cout<<T1<<endl;

You have to define T1 first locally or make it a global variable (not recommended).

int main()
{
double T1=factorial();

cout<<T1<<endl;

return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM