如何使用for循环将值传递给空向量(因子)?
在这段代码中,我试图找到一个数字的因子数,然后将这些因子传递给一个空的向量,但它一直给我零:
#include <stdio.h>
#include <math.h>
int main(void)
{
int facVar = 57;
int S;
double numFact = 0;
int k;
int factors1[4];
for (S = 1; S <= facVar; S = S + 1)
{
if (facVar % S == 0)
{
numFact = numFact + 1;
}
}
int factNum = numFact;
int factors[factNum];
int indices[factNum];
int i;
printf("the number of factors is %.lf \n", numFact);
for (k = 0; k < factNum; k++)
{
factors[k] = S;
}
for (k = 0; k < factNum; k++)
{
printf("factors are %.lf", factors[k]);
}
return 0;
}
答案 0 :(得分:0)
首先,您无需致电:
#include <math.h>
在第一个循环之后,检查您不将数字存储在数组中的因子:
for(S=1 ; S <= facVar ; S = S + 1){
if(facVar % S == 0){
numFact = numFact + 1;
}
}
因此您需要将因子存储在数组因子中。 该程序可帮助您获得所需的结果:
#include <stdio.h>
#include <stdlib.h>
int main(void){
int facVar = 57;
int S, k;
int numFact = 0;
for(S = 1, k = 0 ; S <= facVar ; S++){
if(facVar % S == 0){
numFact++;
}
}
int factors[numFact];
for(S = 1, k = 0 ; S <= facVar ; S++){
if(facVar % S == 0){
factors[k] = S;
k++;
}
}
printf("the number of factors is: %d \n" , numFact);
for(k = 0; k < numFact ; k++){
printf("factors are: %d\n" , factors[k]);
}
return 0;
}
答案 1 :(得分:0)
你走在正确的轨道上,你的程序只需要进行一些清理。摆脱浮点数,多余的变量等。另外要计算因子的数量并计算它们是相同的算法,重复两次。 factors[k] = S;
没有任何意义。
工作代码:
#include <stdio.h>
int main(void)
{
const int facVar = 57;
int numFact = 0;
for (int i = 1; i <= facVar; i++)
{
if (facVar % i == 0)
{
numFact++;
}
}
printf("The number of factors is %d \n", numFact);
int factors[numFact];
int fact_n=0;
for (int i = 1; i <= facVar; i++)
{
if (facVar % i == 0)
{
factors[fact_n] = i;
fact_n++;
}
}
printf("The factors are: ");
for (int i = 0; i < numFact; i++)
{
printf("%d ", factors[i]);
}
return 0;
}