Reputation: 357
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;
}
Upvotes: 2
Views: 165
Reputation: 7480
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;
Upvotes: 3
Reputation: 3049
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.
Upvotes: 3
Reputation: 20800
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;
}
Upvotes: 1