简体   繁体   English

为什么我的while循环停止时不会中断?

[英]Why won't my do while loop stop break?

I am trying to make a do-while loop. 我正在尝试做一个do-while循环。 I am trying to get the user input as long as the user's input's length of the digit is less than 13 digits long or greater than 16 digits long. 只要用户输入的数字长度小于13个数字或大于16个数字,我就试图获取用户输入。

Example: 例:
1234 (4 digits) would run the do while loop again, 1234(4位数字)将再次运行do while循环,
123493919295919(14 digits) would stop the loop. 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);
}

What is int in your system? 您的系统中的int是什么? Is it 4 bytes (32 bits)? 是4个字节(32位)吗?

nDigits for type int , that has 32 bits, will be always less than 11 (I mean that INT_MAX which is equal to 2147483647 gives just 10 ), so condition is TRUE (because (nDigits < 13 || nDigits > 16) gives true OR false , that is true ). nDigitsint nDigits (具有32位)将始终小于11(我的意思是等于2147483647 INT_MAX仅给出10 ),所以条件为TRUE(因为(nDigits < 13 || nDigits > 16)给出了true OR false ,即为true )。

So consider changing type for data representation. 因此,请考虑更改数据表示的类型。

Options: 选项:

  1. char[17] to store strings up to 16 characters (inside string you can check that all characters are digits, see isdigit ) char[17]可存储最多16个字符的字符串(在字符串中,您可以检查所有字符是否为数字,请参见isdigit
  2. uint64_t form <stdint.h> (there seems to be no negative card numbers) uint64_t形式<stdint.h> (似乎没有负卡号)

You should take the credit card number as a string, not an int. 您应该将信用卡号作为字符串,而不是整数。

The cs50 Reference Documentation is pretty clear on that: 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; get_int()从标准输入中读取一行文本,并在[-2 ^ 31 + 1、2 ^ get_int()范围内将其作为int返回; if text does not represent such an int, user is prompted to retry. 如果文本不表示该int,则提示用户重试。 Leading and trailing whitespace is ignored. 开头和结尾的空格将被忽略。 For simplicity, overflow is not detected. 为简单起见,未检测到溢出。 If line can't be read, returns INT_MAX. 如果无法读取行,则返回INT_MAX。

As stated by @VolAnd, this terminates in a signed int32 which has always less than 11 digits and could even be negative... 如@VolAnd所述,这终止于一个有符号的 int32,该整数始终小于11位,甚至可能为负。

I changed the ints to longs and it works. 我将整数更改为longs,并且可以使用。 That is what cs50 wants us to use. 这就是CS50希望我们使用的。 Thanks for the help to everyone! 感谢大家的帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM