c - 程序在 C 中的 if 语句之前关闭
问题描述
参数不通过if 语句,我不知道为什么。
在某些情况下,这个程序应该给你“你还有多少年?” ,考虑到您对大陆的预期寿命估计。
您输入的参数是:年龄、大陆和性别。当我执行它时,我可以输入参数,然后它就停止工作。
#include<stdio.h>
int main(){
unsigned char gender,cont; //cont=Continent
char male,female,America,Oceania,Europe,Africa,Asia;
int age,le; //le=Life expectancy
printf("Insert Continent\n");
scanf("%s",&cont);
printf("Insert Gender\n");
scanf("%s",&gender);
printf("Insert Age\n");
scanf("%d",&age);
//for females
if (gender==female) {
if(cont==America) {
if(80-age<0) {
le=80-age;
printf("Outlived life expectancy by:\t",le);
} else {
le=80-age;
printf("You are expected to live ",le," more years");
}
}
if(cont==Oceania) {
if(80-age<0) {
le=80-age;
printf("Outlived life expectancy by:\t",le);
} else {
le=80-age;
printf("You are expected to live ",le," more years");
}
}
if(cont==Europe) {
if(82-age<0) {
le=82-age;
printf("Outlived life expectancy by:\t");
} else {
le=82-age;
printf("You are expected to live ",le," more years");
}
}
if(cont==Asia) {
if(74-age<0) {
le=74-age;
printf("Outlived life expectancy by:\t");
} else {
le=74-age;
printf("You are expected to live ",le," more years");
}
}
if(cont==Africa) {
if(64-age<0) {
le=64-age;
printf("Outlived life expectancy by:\t");
} else {
le=64-age;
printf("You are expected to live ",le," more years");
}
}
}
return 0;
}
解决方案
您将整个字符串存储在只分配了一个字符的内存中。这是“缓冲区溢出”并导致未定义的行为。
不要将它们分配为单个字符(类型char
),而是尝试将它们分配为字符数组(例如,unsigned char cont[128];
)。我还建议使用fgets()
字符串输入,而不是使用scanf()
说明%s
符。
此外,不要cont == America
用于比较字符串。该strcmp()
功能是这项工作的正确工具。
最后,您永远不会将您在此处使用的变量定义为常量(如America
)。您需要定义America
(变量)(可能为"America"
)或cont
直接与您正在测试的字符串进行比较(再次,可能"America"
)
int main(void) {
const unsigned char *America="America";
unsigned char cont[128];
...
fgets(cont, 128, stdin);
...
if (strcmp(cont, America) == 0) {
...
}
...
}
推荐阅读
- dart - Flutter - 使用 package_info 在 iOS 中获取应用程序版本
- javascript - 将具有相同值的键相乘
- java - 从 Java 8 更新到 OpenJdk 11.0.2 时 intellij maven 中出现错误“找不到 zip END 标头”
- vue.js - 在 vuejs 中将路由前附加到模板
- java - 将项目转换为 Maven 后图像消失了
- node.js - 使用 INFURA 调用智能合约函数
- node.js - 同步流输出
- .net - AutoFixture:为生成的所有随机日期指定边界(或设置为“现在”)
- c++ - 成对的可变参数模板(命名元组)
- typescript - 汇总是否支持汇总配置文件中的打字稿?