我是一名中级Python程序员,但我正在努力学习C.迄今为止,这是一个非常令人沮丧的经历。为什么printf在我的简单脚本中产生奇怪的输出?
为什么这个简单的代码...
#include <stdio.h>
#include <string.h>
char name[15] = "George Lopez"; /* string representing your name */
char birthday[6] = "01-30-92"; /* string representing your bday */
int phone_number; /* declair int representing phone number */
int main() {
phone_number = 2222223333; /* int representing your phone number */
printf("You said your name was: %s\n", name);
printf("And your birthday is %s?\n", birthday);
printf("And, so I can call you, your number is %d\n", phone_number);
return(0); /* exit program normally */
}
产生这种输出时的电话号码是2222223333:
You said your name was: George Lopez
And your birthday is 01-30-92?
And, so I can call you, your number is -2072743963
,该输出将电话号码为9992223333:
error: 4_1_myinfo.c:16:3: warning: overflow in implicit constant conversion [-Woverflow]
phonenumber = 9992223333;
而这个输出当电话号码是1112223333:
You said your name was: George Lopez
And your birthday is 01-30-92?
And, so I can call you, your number is 1112223333
我怀疑这跟下用整数如何交易的事情。也许,C中的ints的最大长度比python中的ints小,这导致了wanky输出?
超出数组范围:'char birthday [6] =“01-30-92”;',导致未定义的行为。 – hmjd 2014-10-20 16:37:20
'生日'应该会导致编译时的强制性诊断。如果你(可以做)忽略它,它不是一个有效的字符串,所以将它作为字符串传递给'printf'就是UB。 – Deduplicator 2014-10-20 16:41:00
尽管它表示为一串数字,但电话号码并非真正的数字。也使用一个字符串。 – chepner 2014-10-20 16:45:18