如何访问循环外的变量? [英] How do I access variable outside the loop?

查看:85
本文介绍了如何访问循环外的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#包括<&的iostream GT; 
using namespace std;
int fact(int n)
{
int i = 5;
int c = n / i;
while(c!= 0)
{
i = i * i;
c + = n / i;
返回c;
}
返回0;
}
int main(){
long t;
unsigned int a [100001],x [100001];
cin>> t;
for(int i = 0; i< t; i ++)
{
cin>> a [i];
int c = a [i];
x [i] =事实(c);
}
for(int i = 0; i< t; i ++)
{
cout<< x [i]<< endl;
}
}



问题是在一组数字的阶乘中打印尾随零,数字可能高达100000。但是对于4位数或以上的数字,我似乎得到了错误的答案。



我尝试了什么:



我试过简单地将返回c语句放在循环之外,但这会使代码进入无限循环。

解决方案

你的析法例程看起来不正确,而while循环只会进行一次迭代。因子N是1 * 2 * 3 ... * N.你还需要摆脱那两个巨大的数组,它们没有用处。你的程序的逻辑应该是:

获取尝试次数
DO
获取下一个数字
计算阶乘
显示数字和阶乘
设置尝试次数=(尝试次数 - 1)
如果尝试次数为零,则中断
重复
END DO


#include<iostream>
using namespace std;
int fact(int n)
{
   int i=5;
   int c=n/i;
   while(c!=0)
   {
    i=i*i;
    c+=n/i;
    return c;
   }
   return 0; 
}
int main(){
    long t;
    unsigned int a[100001],x[100001];
    cin>>t;
    for(int i=0;i<t;i++)
    {
        cin>>a[i];
        int c=a[i];
        x[i]=fact(c);
    }
    for(int i=0;i<t;i++)
    {
    cout<<x[i]<<endl;
    }
}


The problem is to print the trailing zeroes in the factorial of a set of numbers and the numbers could be upto 100000. But I seem to get an incorrect answer for numbers with 4 digits or above.

What I have tried:

I tried simply putting the return c statement outside the loop but that makes the code go into infinite loop.

解决方案

Your factorial routine does not look correct, and the while loop will only ever do one iteration. Factorial N is 1*2*3...*N. You also need to get rid of those two huge arrays, they serve no purpose. The logic for your program should be:

Get number of tries
DO
    Get next number
    Calculate the factorial
    Display the number, and the factorial
    Set number of tries = (number of tries - 1)
    If number of tries is zero, break
    Repeat
END DO


这篇关于如何访问循环外的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆