首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >函数在每次执行中返回不同的值。

函数在每次执行中返回不同的值。
EN

Stack Overflow用户
提问于 2021-09-30 14:53:53
回答 1查看 70关注 0票数 1

我在编码方面有点新,我遇到了一个逻辑错误。目标是创建一个函数来测试数字是否可以从2整除到10。然而,正如我测试过的那样,userInput变量返回正确的值,但是函数的值确实改变了每次执行。以下是代码:

代码语言:javascript
复制
#include <stdio.h>

int testDivisible(int a) {
    int checker; // checker is intended for counting divisible numbers between 2-10; if returned > 0, then not divisible

    for (int i=2; i<=10; i++) {
        if (a % i == 0) {
            checker = checker + 1;
        }
    }

    return checker;
}

int main() {
    int userInput;

    printf("Enter number: ");
    scanf("%d", &userInput);
    int x = testDivisible(userInput);

    if (x > 0) {
        printf("Is divisible by 1 to 10\n");
    }
    else {
        printf("Is not divisible by 1 to 10\n");
    }

    printf("%d\n", userInput); // intended for testing
    printf("%d", x); // intended for testing
}

但是,当我编译和运行代码时,结果是:

执行1:

代码语言:javascript
复制
Enter number: 17
Is divisible by 1 to 10
17
847434400

执行2:

代码语言:javascript
复制
Enter number: 17
Is not divisible by 1 to 10
17
-1002102112
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-30 14:55:23

在你的代码中,

代码语言:javascript
复制
 int checker; 

是一个自动局部变量,没有显式初始化。因此,它在indeterminate.中包含的初始值

必须将值初始化为0

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69394428

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档