在完成作业时,我必须弄清楚如何检查输入的前两个数字是否有特定的组合。虽然我知道该怎么做,但我的代码的第一部分似乎有一个错误。我想通过在输入大于2时将输入除以10来"隔离"前两个数字。我写了这段代码
do
{
card_number = card_number / 10;
}
while (card_number > 2);
例如,我期望结果是'45',但每次我运行代码并使用printf来查看结果时,唯一返回的是零。
如果您试图隔离card_number
的前两位数字,那么您的条件应该检查长度的值为2,而不是值. 另一种方法是,如果该值大于100,则继续除以10。
#include <stdio.h>
int main(void) {
int card_number = 450;
printf("%in", card_number);
while(card_number > 100) {
card_number = card_number / 10;
}
printf("%in", card_number);
return 0;
}
(由于您试图分离前两位数字,因此我假设该值开始时大于100)
已更新为" isolate">
我想这就是你想要的…
int main() {
//TEST CASES = Longer and Shorter than 2 digits
//Comment and uncomment c_num as required for testing both cases
long c_num = 1234567812345678;
//long c_num = 12;
int count = 0;
long n = c_num;
long long n1 = c_num, n2 = c_num; // n2 will hold the first two digits.
while (n) {
n2 = n1;
n1 = n;
n /= 10;
}
printf("The first 2 numbers of the long are %lldn", n2);
/* Run loop till num is greater than 0 */
do {
/* Increment digit count */
count++;
/* Remove last digit of 'num' */
c_num /= 10;
}
while (c_num != 0);
printf("Total digits: %dn", count);
if (count > 2) {
/* Do work */
printf("Total digits is more than 2");
} else {
/*Do other work */
printf("Total digits is NOT more than 2");
}
return 0;
}