gpt4 book ai didi

c - 如何使用循环找到一对加起来也达到一定总和的除数?

转载 作者:行者123 更新时间:2023-11-30 16:05:41 26 4
gpt4 key购买 nike

给定两个数字 n 和 q,我想找到两个数字 m 和 p,使得 n=m*p 且 q= m+p。我编译了代码,但即使输入的值有效,它每次都会返回错误消息。循环有问题吗?

编辑**输入n:100输入q:25

即使 m=20, p=5 有效,仍然返回错误消息

#include <stdio.h>

int main(void){


int *mAddress = NULL;
int *pAddress = NULL;

int n;
printf("enter integer: ");
scanf("%d", &n);

int q;
printf("enter query number: ");
scanf("%d", &q);

int m;
int p;
for (m=1; m<=n; m++){
if(n%m == 0){
p = n/m;
if (m+p == q){
mAddress = &m;
pAddress = &p;
printf("The values are %d %d", m, p);
break;
}
else{
printf("could not find any numbers");
break;
}

}

}

最佳答案

如果您第一次没有找到它,则不应中断循环。相反,您应该继续为每个 n%m == 0 情况发生这种情况。

最终,当您知道没有找到任何内容时,会打印错误消息。

我添加了一个 bool 值来保存您是否找到一对,并用它来打印错误消息。

#include <stdio.h>
#include <stdbool.h>

int main(void){


int *mAddress = NULL;
int *pAddress = NULL;

int n;
printf("enter integer: ");
scanf("%d", &n);

int q;
printf("enter query number: ");
scanf("%d", &q);

int m;
int p;
bool found = false;
for (m=1; m<=n; m++){
if(n%m == 0){
p = n/m;
if (m+p == q){
mAddress = &m;
pAddress = &p;
printf("The values are %d %d", m, p);
found = true;
break;
}
}
}

if (!found) {
printf("could not find any numbers");
}
}


Try it out yourself

关于c - 如何使用循环找到一对加起来也达到一定总和的除数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60219353/

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