gpt4 book ai didi

c - 在 while 循环中重新扫描并分配变量

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

我是编码新手,因此对于任何无知,我深表歉意,但我的程序遇到了两个问题。目标是提示用户输入测试数字,运行测试,并输出该数字是否“完美”。之后,系统会提示用户继续测试新号码或结束程序。我遇到两个问题。 1. 无论输入'y'还是'n',while循环都会继续运行。 2. userInput 不会重新分配,并继续使用与第一个输入相同的输入值运行。任何帮助将不胜感激。

void perfectNumber(int userInput) {

int divisor = 0;
int i;
int totalSum = 0;
char cont;

for (i = 1; i < userInput; i++) {
divisor = userInput % i;
if (divisor == 0) {
totalSum = totalSum + i;
}
}

if (totalSum == userInput) {
printf("Number %d is perfect\n", userInput);
}
else {
printf("Number %d is not perfect\n", userInput);
}
printf("Do you want to continue (y/n)? ");
scanf("%c\n", &cont);
}

int main(void) {
int userInput;
char cont = 'y';

while (cont == 'y' || cont == 'Y') {
printf("Enter a perfect number: ");
scanf("%d", &userInput);
perfectNumber(userInput);
}
printf("Goodbye\n");

return(0);
}

最佳答案

问题是您认为 cont 是唯一的一个变量。

事实是,您有两个 cont 变量,它们唯一共享的就是名称相同。它们是两个具有唯一地址的不同变量。

一个属于main函数,另一个属于perfectNumber函数。

返回唯一的 cont 变量怎么样?

#include <stdio.h>
char perfectNumber(int userInput) {
int divisor = 0;
int i;
int totalSum = 0;
char cont;

for (i = 1; i < userInput; i++) {
divisor = userInput % i;
if (divisor == 0) {
totalSum = totalSum + i;
}
}

if (totalSum == userInput) {
printf("Number %d is perfect\n", userInput);
}
else {
printf("Number %d is not perfect\n", userInput);
}
printf("Do you want to continue (y/n)? ");
scanf(" %c", &cont);
return cont;
}

int main(void) {
int userInput;
char cont = 'y';

while (cont == 'y' || cont == 'Y') {
printf("Enter a perfect number: ");
scanf("%d", &userInput);
cont = perfectNumber(userInput);
}
printf("Goodbye\n");

return(0);
}

请注意,您缺少#include 防护,我添加了它。

关于c - 在 while 循环中重新扫描并分配变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54499136/

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