Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/docker/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我正在尝试创建一个c程序,用数组计算一个数字的因子,出了什么问题? intmain() { 整数系数[50],i,数字; printf(“请输入一个数字:”); scanf(“%d”,&number);//从用户处获取值 对于(i=0;i_C - Fatal编程技术网

我正在尝试创建一个c程序,用数组计算一个数字的因子,出了什么问题? intmain() { 整数系数[50],i,数字; printf(“请输入一个数字:”); scanf(“%d”,&number);//从用户处获取值 对于(i=0;i

我正在尝试创建一个c程序,用数组计算一个数字的因子,出了什么问题? intmain() { 整数系数[50],i,数字; printf(“请输入一个数字:”); scanf(“%d”,&number);//从用户处获取值 对于(i=0;i,c,C,不要使用i作为存储因子的索引,因为您没有填充非因子的数组元素。请使用其他变量保存数组索引。由于您没有初始化数组,因此在打印这些元素的值时会得到不确定的值。如果要将其初始化为0,循环将在到达第一个非因子时停止,因为在到达0之前一直在循环 对数组索引和您正在测试的因子使用不同的变量。这样,您就不需要一直将1添加到因子中,您可以使用索引的最终值作为打印循环的限制 int main() { int arrFactors[50] , i , number ; printf("pleas

不要使用
i
作为存储因子的索引,因为您没有填充非因子的数组元素。请使用其他变量保存数组索引。由于您没有初始化数组,因此在打印这些元素的值时会得到不确定的值。如果要将其初始化为
0
,循环将在到达第一个非因子时停止,因为在到达
0
之前一直在循环

对数组索引和您正在测试的因子使用不同的变量。这样,您就不需要一直将1添加到因子中,您可以使用索引的最终值作为打印循环的限制

int main()
{
    int arrFactors[50] , i , number ; 

    printf("please enter a number : ");
    scanf("%d",&number); // take the value from the user

    for (i = 0 ; i <= number ; i++) // loop for storing the factors 
    {
        if(number%(i+1)==0) // condition to check if number have factors from 1 to number
            arrFactors[i]=(i+1); // if the condition true then save the value to the arr
    }

    printf("the Factors of %d = " ,number);

    for(i=0 ; arrFactors[i]=='\0' ; i++) // printing the arr 
    {
        printf("%d\t",arrFactors[i]);
    }

    return 0;
}
#包括
int main()
{
整数系数[50],i,数字,j=0;
printf(“请输入一个数字:”);
scanf(“%d”,&number);//从用户处获取值

对于(i=1;我对OP给出了一个很好的答案。此外,对于你找到的每一个,你也会得到两个因子(除非数字是平方的,并且你找到了平方),但是你看起来并不关心速度。从数字上来说,你不需要在sqrt(n)上面搜索对于n的因子,它在其他实际应用中节省了时间。我不认为他只是试图找到素因子,只是所有的除数。它包括数字本身,尽管这可以作为一个特例添加。伟大的@Barmar先生,你知道了,使用var.I作为计数器,也作为索引是一个大错误?什么是ab在第二个循环中,这个条件是完全错误的吗?但是你在我的问题上做得很好,我理解你的解决方案,@Bwebb是的,我不在乎速度,我是一个初学者,我a,试图用其他方法解决这个问题,让编程更广为人知,我大约1个月前开始使用C。是的,这是一个很大的错误,因为你ere跳过数组元素,无法判断跳过了哪些元素。
#include <stdio.h>

int main()
{
    int arrFactors[50] , i , number, j = 0 ; 

    printf("please enter a number : ");
    scanf("%d",&number); // take the value from the user

    for (i = 1 ; i <= number ; i++) // loop for storing the factors 
    {
        if(number % i == 0) // condition to check if number have factors from 1 to number
            arrFactors[j++]=i; // if the condition true then save the value to the arr
    }

    printf("the Factors of %d = " ,number);

    for(i=0 ; i < j ; i++) // printing the arr 
    {
        printf("%d\t",arrFactors[i]);
    }
    printf("\n");
    return 0;
}