重新扫描和while循环变量赋值

问题描述 投票:-1回答:2

我是新来的编码,所以我对任何的无知道歉,但我正在为两个问题,我的计划。我们的目标是提示用户输入测试号,运行测试,并输出数量是否是“完美”。之后,系统会提示用户继续测试新号码或结束程序。我遇到的两个问题。 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);
} 
c
2个回答
2
投票

问题是你认为cont是只有一个变量。

事实是,你有两个cont变量,只有他们分享一点是相同的名称。他们以独特的不会忽略两个不同的变量。

一个属于主要功能,另外一个属于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后卫,我加入吧。


0
投票

contmain(这是不一样的cont perfectNumber)从不在循环内改变,并且环路保护仅取决于该cont。类似的事情瓦特/两个userInputs。

© www.soinside.com 2019 - 2024. All rights reserved.