【发布时间】:2018-04-27 16:40:15
【问题描述】:
我正在尝试通过 edX/iTunesU 完成哈佛 CS50 课程中的 pset1,并且我正在尝试对 Luhn's algorithm 进行编程。下面的代码非常不完整,但我想知道如何在 for 循环中使用 pow() 并在 pow() 中使用 i。据推测,还有另一种方法可以不使用pow() 来编写 Luhn 的算法,但探索这种方法让我注意到了这个问题。有什么建议吗?
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main(void) {
long long c = 1234123412341234;
long long temp_c = c;
long long temp_c_one = c;
long long c_one_x = 0;
int count = 0;
while (temp_c > 0LL) {
temp_c = temp_c / 10LL;
count++;
}
for (int i = 0; i < count; i++) {
c_one_x = (temp_c_one % (pow(10, (i + 1))) / (pow(10, i));
count--;
}
}
【问题讨论】:
-
double pow(double)对浮点数很有用。对于整数数学问题,请考虑仅使用整数函数并避免各种整数 FP 问题。 -
请注意,每次迭代都可以使用单乘 10。
-
请注意,Luhn 的算法从右到左进行,并且此代码有效地首先考虑最高有效位。首先找到最低有效数字实际上是使用
while (c) { dig = c%10; use(dig); c /= 10; }更容易的代码