使用模运算符我缺少什么?
这是我第二次从模运算符得到令人困惑的结果,所以我确信我一定错过了它是如何工作的,我在这里做错了什么,导致我得到了错误的答案?该函数应该接受一个数字并将其数字作为指向数组的指针返回(其中第一个元素表示它有多少位数字)。它实际上做的是返回一个数组,其中第一个之后的所有索引都包含原始数字。
int *getDigits(int n)
{
int digits = log10(n)+1;
int i = 1;
int *digit = malloc((digits+1) * sizeof(int));
if (digit == NULL) { printf("error\n"); }
digit[0] = digits;
for (i = 1; i < digits+1; i++) {
int blah = (int) pow(10,i);
printf("digit[%d] = remainder of %d divided by %d\n",i,n,blah);
digit[i] = (n%blah);
printf("%dth digit %d\n",i,n);
}
return digit;
}
当我运行它时,每次迭代看起来都是这样的:
checking 500996
digit[1] = remainder of 500996 divided by 10
1th digit 500996
digit[2] = remainder of 500996 divided by 100
2th digit 500996
digit[3] = remainder of 500996 divided by 1000
3th digit 500996
digit[4] = remainder of 500996 divided by 10000
4th digit 500996
digit[5] = remainder of 500996 divided by 100000
5th digit 500996
digit[6] = remainder of 500996 divided by 1000000
6th digit 500996
This is the second time I have got confusing results from the modulo operator, so I am sure I must be missing something about how it works, what am I doing wrong here that is getting me the wrong answers? This function is supposed to take a number and return its digits as a pointer to an array (where the first element says how many digits long it is). What it actually does is returns an array where all the indexes after the first contain the original number.
int *getDigits(int n)
{
int digits = log10(n)+1;
int i = 1;
int *digit = malloc((digits+1) * sizeof(int));
if (digit == NULL) { printf("error\n"); }
digit[0] = digits;
for (i = 1; i < digits+1; i++) {
int blah = (int) pow(10,i);
printf("digit[%d] = remainder of %d divided by %d\n",i,n,blah);
digit[i] = (n%blah);
printf("%dth digit %d\n",i,n);
}
return digit;
}
When I run it each iteration looks something like this:
checking 500996
digit[1] = remainder of 500996 divided by 10
1th digit 500996
digit[2] = remainder of 500996 divided by 100
2th digit 500996
digit[3] = remainder of 500996 divided by 1000
3th digit 500996
digit[4] = remainder of 500996 divided by 10000
4th digit 500996
digit[5] = remainder of 500996 divided by 100000
5th digit 500996
digit[6] = remainder of 500996 divided by 1000000
6th digit 500996
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看来您总是在打印您的输入:
It appears that you're always printing your input:
您将模数的结果存储在 digital[i] 中,但不打印:
n % blah
不会修改 n 或 blah,它只返回结果。You store the result of the modulo in digit[i], but you do not print that:
n % blah
does not modify n or blah, it only returns the result.