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]);
}
}
但是发生了一些奇怪的事情,因为 main 甚至没有到达打印“测试”,因为没有输出......为什么?
编辑:
好的,我通过添加printf 修复了 printf 问题\n
。
但是,digitcont 功能似乎仍然不起作用。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' );
推荐阅读
- c++ - 如何为 armv7l 架构构建 Qt 项目?
- html - 在 html 中从用户那里获取输入并转换为 python 列表
- python - 如何在python中按索引获取2个列表的总和?
- sql - 如何使 SQL 自动将表中的某些行复制到同一数据库中的另一个表?
- c# - 为不同的accesstoken实现多个AuthenticationHandler
- python - Python 的 zipfile 库无法提取受密码保护的文件
- python-3.x - API 不再连接
- pandas - 基于另一列中的分组连接数据框列中的字符串
- xojo - xojo 中是否有不重复相同行的方法?
- python - 如何在 sagemaker 中运行 python 脚本(其中编写了一些函数)?