[英]I am trying to create a c program to get the factors of a number with array , what is going wrong?
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;
}
我正在嘗試使用數組獲取數字的因數有什么問題?
不要使用i
作為索引來存儲因子,因為您沒有填充不是因子的數組元素。 使用不同的變量來保存數組索引。 由於您沒有初始化數組,因此在打印這些元素的值時會得到不確定的值。 如果您要將其初始化為0
,則循環將在到達第一個非因數時停止,因為您一直在循環直到到達0
。
對數組索引和要測試的因子使用不同的變量。 那么就不用一直給因子加1了,就可以用索引的最終值作為打印循環的極限了。
#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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.