为什么我的 do while 循环不会中断?

Why won't my do while loop stop break?

我正在尝试制作一个 do-while 循环。只要用户输入的数字长度小于 13 位或大于 16 位,我就会尝试获取用户输入。

示例:
1234(4 位数字)会 运行 do while 循环,
123493919295919(14 位数字)将停止循环。

#include <cs50.h>
#include <stdio.h>
#include <math.h>

int main(void)
{
    int n;
    int nDigits;
    do
    {
        n = get_int("Please enter your credit card number:\n");
        nDigits = floor(log10(abs(n))) + 1;
    }
    while (nDigits < 13 || nDigits > 16);
}

你的系统中 int 是什么?是4字节(32位)吗?

nDigits 对于类型 int,有 32 位,将始终小于 11(我的意思是 INT_MAX 等于 2147483647 只给出 10), 所以条件为 TRUE (因为 (nDigits < 13 || nDigits > 16) 给出 true OR false, 即 true).

因此考虑更改数据表示的类型。

选项:

  1. char[17] 存储最多 16 个字符的字符串(在字符串中你可以检查所有字符都是数字,参见 isdigit
  2. uint64_t形式<stdint.h>(好像没有负卡号)

您应该将信用卡号作为字符串,而不是整数。

cs50 参考文档对此非常清楚:

get_int() reads a line of text from standard input and returns it as an int in the range of [-2^31 + 1, 2^31 - 2], if possible; if text does not represent such an int, user is prompted to retry. Leading and trailing whitespace is ignored. For simplicity, overflow is not detected. If line can’t be read, returns INT_MAX.

如@VolAnd 所述,这终止于 signed int32,它始终少于 11 位数字,甚至可能为负数...

我将整数更改为长整数并且它有效。这就是cs50要我们使用的。感谢大家的帮助!