简体   繁体   English

无法从 function 返回值?

[英]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". function 应该返回 T1 并从 main 中取出它,但它总是给我一个错误“T1 是未声明的标识符”。 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).每个 function 只知道它的局部变量(和全局变量,您没有任何定义)。 You have to create a variable for the result from in main:您必须为 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 .因为 T1 没有在 main() scope 下定义,所以它只在 function阶乘的 scope 下定义。

You should do this instead:你应该这样做:

cout<<factorial()<<endl;

or define T1 like this within your main function:或在您的主要function 中像这样定义 T1:

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

You have to define T1 first locally or make it a global variable (not recommended).您必须先在本地定义T1或将其设为全局变量(不推荐)。

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

cout<<T1<<endl;

return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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