You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言中无法打印Luhn_validity返回值的问题排查

Why Isn't Your Luhn_validity Value Printing Correctly?

Let’s break down the issue and fix it step by step:

The Root Cause: Mismatched Format Specifier

You’re storing Luhn_validity as a char type, assigning it 0 or 1 to represent valid/invalid status. But when you print it with printf("%c returned from line 119\n", Luhn_validity);, you’re using the %c format specifier—which is designed to output ASCII characters, not integer values.

In ASCII, 0 corresponds to a non-printable null character, and 1 corresponds to a non-printable "Start of Header" control character. That’s why you don’t see the expected 0 or 1 in your output.

Fixes You Can Apply

You have two straightforward ways to resolve this:

1. Use the Correct Format Specifier

Keep Luhn_validity as a char (since it’s just a small integer), but switch to the %d format specifier when printing. %d treats the char as a decimal integer, so it will print the actual 0 or 1 value:

printf("%d returned from line 119\n", Luhn_validity);

2. Use a More Appropriate Variable Type

For boolean-like status values in C, using int is more conventional (or bool from <stdbool.h> if you’re using C99 or later). This makes your code more readable and avoids confusion with character data:

// Option 1: Use int
int Luhn_validity = 0;

// Option 2: Use bool (requires #include <stdbool.h>)
bool Luhn_validity = false;

When using int or bool, %d will still correctly print 0 or 1 for invalid/valid status.

Bonus: Critical Logic Bug to Fix

While we’re at it, there’s a dangerous typo in your get_credit_card_status function:

// This is an assignment, not a comparison!
if (((credit_card_number < 350000000000000) && (340000000000000 <=credit_card_number)) && (Luhn_validity=1))

Luhn_validity=1 sets the variable to 1 instead of checking if it equals 1. You need to use the equality operator == here:

if (((credit_card_number < 350000000000000) && (340000000000000 <=credit_card_number)) && (Luhn_validity == 1))

This bug would have made your American Express check always pass, regardless of actual Luhn validity.

Extra Suggestion

Storing credit card numbers as long long can lead to overflow for longer card numbers (some cards have 19 digits, which is right at the limit of long long's capacity). For more robust handling, consider using a string to store the card number instead.

内容的提问来源于stack exchange,提问作者Gauthier Delvaulx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:03:04