【问题标题】:new to C; using pow() in a for loopC 新手;在 for 循环中使用 pow()
【发布时间】: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; } 更容易的代码

标签: c for-loop cs50 pow luhn


【解决方案1】:

您可以避免使用 pow,方法是使用一个计数器,每次循环迭代乘以 10。

#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;

  long long pwr = 1; // 10^0 = 1
  int count = 0;

  while (temp_c > 0LL) {
    temp_c = temp_c / 10LL;
    count++;
  }

  // TODO: Don't think you should decrement count in this loop
  for (int i = 0; i < count; i++) {
    c_one_x = (temp_c_one % (pwr * 10)) / pwr;
    count--;
    pwr *= 10;
  }
}

但是,我不相信你已经产生了一个好的 Luhns 算法实现,所以我的建议是:

// Better Luhn's algorithm
int luhn( long long cc) {
  unsigned long check = 0;
  unsigned int digit;
  for (int i = 0; cc > 0; i++) {
    digit = cc % 10;
    // double every second digit
    if (i % 2) {
      digit *= 2;
      digit = (digit >= 10) ? (digit + 1) % 10 : digit;
    } 
    check += digit; 
    cc = cc/10; // next CC digit.
  }
  return check;
}

int main (void) {
  long long c = 1234123412341234;

  print "Result is : %d", luhn(c));
}

【讨论】:

    猜你喜欢
    • 2012-05-13
    • 2015-06-26
    • 2020-07-06
    • 2016-03-13
    • 2011-10-13
    • 2018-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多