“白富美”问题背后的C语言知识

    xiaoxiao2022-07-07  191

    “白富美”问题

    “白富美”问题描述一、错误方法1.错误代码2.错误原因 二、正确方法1.python代码2.C代码3.C代码 三、总结

    “白富美”问题描述

    “白富美”其实很简单,就是三组printf()和scanf()组成的输入输出,以及if判断,最终输出的是“你是白富美!”或者“你不是白富美!”

    一、错误方法

    1.错误代码

    1 #include<stdio.h> 2 #include<string.h> 3 int main() 4 { 5 int money = 0; 6 char *color = NULL, *beautiful = NULL; 7 printf("你白吗?"); 8 scanf("%s",color); 9 printf("请输入你的财产总额:"); 10 scanf("%d",&money); 11 printf("你美吗?"); 12 scanf("%s",beautiful); 13 if(strcmp(color,"白") == 0 && money > 100 && strcmp(beautiful,"美") ==0) 14 printf("\n你是白富美!"); 15 else 16 printf("\n你不是白富美!"); 17 return 0; 18 }

    错误运算结果:

    2.错误原因

    上面这段代码的问题,主要在于没有给定义的指针变量分配内存空间,导致scanf()函数无法完成输入操作。虽然在定义指针变量时给指针变量赋值NULL,但实际上NULL表示0,是个空地址。所以,scanf()函数检测到空地址后,就停止执行其输入操作了。

    二、正确方法

    发现了问题后,我用python和C两种语言写了代码,不得不说,python的代码是真的简单,而且不需要考虑一些底层的问题。

    1.python代码

    1 color = input("你白吗?") 2 money =int(input("请输入你的财产总额:")) 3 beautiful = input("你美吗?") 4 print() 5 if color == "白" and money > 1000 and beautiful == "美": 6 print("你是白富美!") 7 else: 8 print("你不是白富美!")

    python运算结果:

    你白吗?白 请输入你的财产总额:1001 你美吗?美 你是白富美!

    2.C代码

    1 #include<stdio.h> 2 #include<string.h> 3 int main() 4 { 5 int money = 0; 6 char color[100], beautiful[100]; 7 printf("你白吗?"); 8 scanf("%s",color); 9 printf("请输入你的财产总额:"); 10 scanf("%d",&money); 11 printf("你美吗?"); 12 scanf(" %s",beautiful); 13 if(strcmp(color,"白") == 0 && money > 100 && strcmp(beautiful,"美") ==0) 14 printf("\n你是白富美!"); 15 else 16 printf("\n你不是白富美!"); 17 return 0; 18 }

    3.C代码

    1 #include<stdio.h> 2 #include<string.h> 3 #include<malloc.h> 4 int main() 5 { 6 int money = 0; 7 char *color, *beautiful; 8 color = (char *)malloc(sizeof(char)); 9 beautiful = (char *)malloc(sizeof(char)); 10 printf("你白吗?"); 11 scanf("%s",color); 12 printf("请输入你的财产总额:"); 13 scanf("%d",&money); 14 printf("你美吗?"); 15 scanf(" %s",beautiful); 16 if(strcmp(color,"白") == 0 && money > 100 && strcmp(beautiful,"美") ==0) 17 printf("\n你是白富美!"); 18 else 19 printf("\n你不是白富美!"); 20 return 0; 21 }

    运算结果:

    你白吗?白 请输入你的财产总额:102 你美吗?美 你是白富美!

    三、总结

    1.由于我的能力有限,所在在使用C语言的指针时出错,导致整个程序无法正确运行。 2.在使用scanf()函数时,一定要注意规范。 3.比如输入语句:scanf("%s %c %d", str,&c,&a);,正确的输入方式是:我来了! r 10,即两两之间用空格隔开,因为 scanf()语句里面两两之间就是用空格隔开的,当然也可以换成逗号隔开,对应的输入时也要用逗号隔开。

    最新回复(0)