c - 我的 C 代码有问题。它返回非零值,我不知道为什么
问题描述
我试图弄清楚为什么以及如何返回到非零值?
结构如下:
询问用户喜欢什么 -> 咖啡或茶 -> 如果咖啡/茶 -> 多少杯 -> 0-3/3-20 -> printf's
否则,如果用户没有给出正确的答案-> else'error'。
这是我学校的作业。
#include <stdio.h>
int main()
{
char coff = 'c', tea = 't', answer;
int x = 0;
printf("Do you drink coffee or tea(c/t)?");
scanf("%c", &answer);
if((answer == 'c') || (answer =='t'))
{
printf("How many cups do you drink daily:");
scanf("%d", &x);
if(answer =='c' && x<=2)
{
printf("You don't drink a lot of coffee, do you?");
}
if(answer == 'c' && x>3)
{
printf("You drink a lot of coffee!");
}
if(answer =='t' && x<=2)
{
printf("You do not drink a lot of tea.");
}
if(answer =='t' && x>3)
{
printf("You drink a lot of tea!");
}
}
else
printf("An error occurred in the program!");
return 0;
}
解决方案
考试:
if(answer == 'c' && x>3)
应该是以下之一:
if( answer == 'c' && x >= 3 )
或者
if( answer == 'c' && x > 2 )
因为 3 既不大于 3 也不小于或等于 2。
无论如何,值得您使解决方案过于复杂;它充满了对您已经知道为真的条件的重复测试,以及由于先前的条件为假而对您已经知道为真的事物进行测试。你可以做什么(一个天真的改进):
if(answer =='c' )
{
if( x < 3 )
{
printf("You don't drink a lot of coffee, do you?");
}
else
{
printf("You drink a lot of coffee!");
}
}
else
{
if( x < 3 )
{
printf("You don't drink a lot of tea, do you?");
}
else
{
printf("You drink a lot of tea!");
}
}
我可能会做什么:
if( x < 3 )
{
printf( "You don't drink a lot of %s, do you?",
answer == 'c' ? "coffee" : "tea" ) ;
}
else
{
printf("You drink a lot of %s!",
answer == 'c' ? "coffee" : "tea" ) ;
}
推荐阅读
- javascript - 大型 API 的分页
- c# - 如何在 JetBrains Rider 中添加/使用 C# 库?
- lua - 如何在 OSX 或 32 位 core.so 上安装 32 位 luasocket
- android - 如何导入和同步 BitBucket 项目
- java - 如何在 spring-boot 中获取实体的所有元素?
- angular - 尝试传递请求选项时出错
- c - C 编译器参考实现
- angularjs - 为什么 AngularJS $compile 不执行 javascript 代码?
- angularjs - 在angularjs中编辑内容时取消功能不起作用?
- wordpress - paginate_links() 在查询字符串中显示当前页面