c语言 - 尝试打印具有某些数字长度的数组元素,但 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]);
}
}

但是奇怪的事情正在发生,因为主要甚至没有达到打印"测试",因为没有输出......为什么?

编辑

好的,我通过在printf 中添加n来解决 printf 问题。

但是,数字康特功能似乎仍然不起作用。CPU 提高了 100% 的使用率...

该函数有一个错误。

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' );

没有输出,因为printf()缓冲区它是基于您拥有的重定向的输出。 如果要打印到控制台,printf()使用缓冲区,直到缓冲区填充或换行符,先到什么。 这就是您在终端中看不到任何test消息的原因,因为它缺少n字符。 如果您将输出重定向到文件(并且您能否实时看到文件上发生的事情,那么您应该没有看到testn消息,因为行为是缓冲区,直到缓冲区已满

这就是printf()的工作方式...只需在该 printf 之后fflush(stdout);一行(即使没有n(,您也会在终端中看到输出(好吧,如果忘记在上面的行为中添加它:......或者程序员冲出缓冲区(

最新更新