我的程序中有多个函数。每个函数都有一些条件。如果满足条件,则它将值传递给另一个函数,该函数再次根据某些条件检查该值,并对其进行修改。
第一个函数 [名为 'squarefree()'] 是从 main [显然] 调用的,它进一步调用另一个函数,该函数当然会调用另一个函数,直到进程在最后一个名为 'end()' 的函数处停止。像这样:
#include <iostream>
using namespace std;
int squarefree(int n);
int goodnumber(int sf);
int end(int gn);
int main() {
// your code goes here
int l,r;
cin>>l;
cin>>r;
for(int p=l;p<=r;p++)
{squarefree(p);}
/*int ret=end(int gn); PROBLEM LIES HERE
cout<<ret; */
return 0;
}
int squarefree(int n){
int i;
for(int i=2;i<n;i++)
{
if((n%(i*i))==0)
{
cout<<"number not square free"<<endl;
break;
}
else{
cout<<"number square free"<<endl;
goodnumber(n);
break;
}
}
return 0;
}
int goodnumber(int sf){
cout<<"Sf is:"<<sf<<endl;
int s=0,c=0,flag=0;
for(int j=1;j<=sf;j++)
{
if(sf%j==0)
{
s+=j;
for(int k=2;k<=j/2;++k)
{
if(j%k==0)
{
c++;
}
}
}
}
cout<<"s is:"<<s<<endl;
cout<<"no.of prime numbers dividin s are:"<<c<<endl;
for(int l=2;l<=c/2;++l)
{
if(c%l==0)
{
flag=1;
break;
}
}
if (flag==0)
{cout << "C is a prime number, so this is good number and needs to be passed to next function"<<endl;
end(s);
}
else
{cout << "C is not a prime number"<<endl;
}
return 0;
}
int end(int gn)
{
int sum=0;
sum+=gn;
cout<<"SUm of factors of the good number is:"<<sum<<endl;
return sum;
}
“end()”函数返回一个值和。现在我希望每次运行 main() 函数中的 for 循环时更新这个值总和。例如:第一次迭代的总和为 5,第二次迭代的总和为 10,因此总和为 15,依此类推。
如果能以某种方式将 end 函数返回的值提取到 main 函数中,那就太好了。
最佳答案
看看那些总是返回 0 的返回 int
的函数。您也许可以利用它。
一个简单的例子:
#include <iostream>
int step3(int val)
{
return val * val;
}
int step2(int val)
{
return step3(val + 1);
}
int step1(int val)
{
return step2(val * 2);
}
int main()
{
std::cout << step1(1);
}
但要小心。您可能会发现没有得到任何有效结果的情况,需要通知调用者未找到任何结果。
关于c++ - 如何在不直接调用函数的情况下将值返回给主函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39420291/