首页 > 解决方案 > 尝试打印具有特定数字长度的数组元素,但 main() 似乎没有执行

问题描述

我正在使用此代码。它应该创建一个包含随机值的 30 个元素的数组。然后 digitcont 函数应该计算数字,如果数字是两位,则打印数字。

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

#define SIZE 30

int digitcont(int *num){
    int division;
    int count = 0;
    do {
        division = *num / 10;   // divide by 10
        ++count;                // increase digits count
    } while (division != 0);    // continue until the result is 0.
    if (count == 2){            // if number has 2 digits, it prints the number, else it doesn't print it.
        printf("%d", *num);
    }
    return 0;
}

int main(){
    srand(time(NULL));
    int myarray[SIZE] = {0};
    int randstuff = 0;
    printf("test");                 // it doesn't even prints this
    for (int i=1; i<=SIZE; ++i){
        randstuff = rand() % i;     // takes a random number
        myarray[i-1] = randstuff;   // and puts in the array
        digitcont(&myarray[i-1]);
    }
}

但是发生了一些奇怪的事情,因为 main 甚至没有到达打印“测试”,因为没有输出......为什么?

编辑

好的,我通过添加printf 修复了 printf 问题\n

但是,digitcont 功能似乎仍然不起作用。CPU 使用率提高 100%...

标签: carraysstringpointersprintf

解决方案


该函数有一个错误。

    division = *num / 10;   // divide by 10

*num 的值在循环的迭代中是相同的。

你必须写

int digitcont(int *num){
    int division = *num;
    int count = 0;
    do {
        division = division / 10;   // divide by 10
        ++count;                // increase digits count
    } while (division != 0);    // continue until the result is 0.
    if (count == 2){            // if number has 2 digits, it prints the number, else it doesn't print it.
        printf("%d", *num);
    }
    return 0;
}

同样不清楚为什么函数参数具有指针类型而不是整数类型。

该函数应该只做一件事:计算数字中的位数。函数的调用者将根据函数的返回值决定是否输出消息。

函数的返回值等于 0 没有意义。

并改变这个电话

 printf("test"); 

puts("test"); 

并在循环后输出换行符

putchar( '\n' );

推荐阅读