gpt4 book ai didi

C 在主函数中显示(打印),而在自定义函数中返回值

转载 作者:行者123 更新时间:2023-11-30 17:22:21 25 4
gpt4 key购买 nike

该程序需要让用户在main函数中输入两个数字:m和n。然后需要在自定义函数中计算以 m 开头的 n 的所有因子。然后它需要在主函数中显示/打印这些因素。

重要的是:您不能打印自定义函数中的因子,只能从主函数中打印。也没有全局变量。

我的程序只返回第一个因子(应该输入1(m), 18(n) = 1,2,3,6,9,18)

我在主函数中也遇到了 for() 的问题,我不知道应该使用什么作为限制,因为它返回的值比一个数字的因数数量多很多倍。

#include<stdio.h>
#include <conio.h>

int toti_factori(int x,int y);

main(){
int m,n,i;
printf("intro m si n");
scanf("%d %d",&m,&n);
for(i=m;i<=n;i++)
{
printf("%d ",toti_factori(m,n));
}


}

int toti_factori(int x,int y){
static int i=1;
int t=0;
for(i=1;i<=y;i++){

if(y%i==0){
if(i>=x){
return i;

}
}

}
}

最佳答案

我的建议:

  1. 创建一个可以容纳所有因子的结构体

  2. toti_factori 返回 struct 的对象。

  3. 根据需要使用 struct 的内容。

这是一个工作程序。

#include <stdio.h>
#include <stdlib.h>

typedef struct Factors
{
size_t size;
int* data;
} Factors;

Factors toti_factori(int x, int y);

int main(){
int m, n, i;

printf("intro m si n: ");
scanf("%d %d", &m, &n);

// Get all the factors in one call.
Factors factors = toti_factori(m, n);

// Print the factors.
for ( i = 0; i < factors.size; ++i)
{
printf("%d ",factors.data[i]);
}
printf("\n");

// Deallocate memory before program ends.
free(factors.data);

return 0;
}

Factors toti_factori(int m, int n){
int count = 0;
int index = 0;
Factors factors;

int i = 0;

// Find out the number of factors.
for ( i = m; i <= n; ++i)
{
if ( n%i == 0)
{
++count;
}
}

// Allocate memory for the factors.
factors.size = count;
factors.data = malloc(count*sizeof(*factors.data));

// Gather the factors.
for ( i = m; i <= n; ++i)
{
if ( n%i == 0)
{
factors.data[index] = i;
++index;
}
}

return factors;
}

不使用结构的解决方案

#include <stdio.h>

int toti_factori(int x, int y);

int main(){
int m, n, i;

printf("intro m si n: ");
scanf("%d %d", &m, &n);

// Print the factors.
for ( i = m; i < n; ++i)
{
// Get the next factor and store it in i.
i = toti_factori(i, n);
printf("%d ", i);
}
printf("\n");

return 0;
}

int toti_factori(int m, int n){

int i = 0;
for ( i = m; i <= n; ++i)
{
if ( n%i == 0)
{
return i;
}
}
return i;
}

关于C 在主函数中显示(打印),而在自定义函数中返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28049867/

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