gpt4 book ai didi

c - 如何在空 vector 中传递值?

转载 作者:行者123 更新时间:2023-11-30 16:48:34 24 4
gpt4 key购买 nike

如何使用 for 循环将值传递到空 vector (因子)?

在这段代码中,我试图找到一个数字的因数个数,然后将这些因数传递到一个空 vector 中,但它一直给我零

#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;
}

最佳答案

首先,您不需要调用:

#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;

}

关于c - 如何在空 vector 中传递值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42919092/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com