#include <stdio.h>
int calculate_pizza_share(int number_of_people);
int main() {
int num_of_people;
printf("how many people are shairng this pizza? ");
scanf("%d", &num_of_people);
calculate_pizza_share(num_of_people);
return 0;
}
int calculate_pizza_share(int number_of_people) {
if (number_of_people == 1) {
printf("You get %d slice(s) each\n", 8 / number_of_people);
} else if (number_of_people == 2) {
printf("you get 4 slice(s) each\n");
} else if (number_of_people == 3) {
printf("you get 2 slice(s) each\n");
} else if (number_of_people == 4) {
printf("you get 2 slice(s) each\n");
} else if (number_of_people == 5) {
printf("you get one slice(s) each\n");
} else if (number_of_people == 6) {
printf("you get one slice(s) each\n");
} else if (number_of_people == 7) {
printf("you get one slice(s) each\n");
} else if (number_of_people == 8) {
printf("you get one slice(s) each\n");
}
}
答案 0 :(得分:2)
一行怎么样:
printf("You get %d slice(s) each\n",8 / number_of_people);
你没有得到&#34;一个&#34;而不是&#34; 1&#34;,但我认为简单优先于。
取而代之的是整个if/else
&#34;梯子&#34;可以替换为switch/case
<强>更新强>
解决了我在编辑器中遇到的问题,代码现在已经发布了。
好的,这两种方式都有。我认为单行仍然是最好的,但我用switch
替换了梯子:
#include <stdio.h>
int calculate_pizza_share(int number_of_people);
int
main()
{
int num_of_people;
printf("how many people are shairng this pizza? ");
scanf("%d", &num_of_people);
calculate_pizza_share(num_of_people);
return 0;
}
int
calculate_pizza_share(int number_of_people)
{
#ifndef SWITCH
printf("You get %d slice(s) each\n", 8 / number_of_people);
#else
switch (number_of_people) {
case 5:
case 6:
case 7:
case 8:
printf("You get one slice each\n");
break;
default:
printf("You get %d slice(s) each\n", 8 / number_of_people);
break;
}
#endif
}
答案 1 :(得分:0)
有时if/else if
链是正确的方法,特别是在生成涉及数字量的英语短语时。但是寻找减少条件数量的方法。在此示例中,您实际上只有三个(有效)条件
8/number_of_people
将为所有这些提供正确的答案此外,您应始终假设用户将输入废话(如果有机会)。因此,您需要检查scanf
的返回值,并准备好处理小于1且大于8的数字。
考虑到这一点,这是代码的样子:
#include <stdio.h>
void calculate_pizza_share(int number_of_people)
{
if (number_of_people < 1)
printf("You need some people to eat that pizza\n");
else if (number_of_people == 1)
printf("You get the whole pizza\n");
else if (number_of_people <= 4)
printf("You get %d slices each\n", 8 / number_of_people);
else if (number_of_people <= 8)
printf("You get one slice each\n" );
else
printf("You need to order more pizza\n");
}
int main( void )
{
int num_of_people;
printf("how many people are sharing this pizza? ");
if (scanf("%d", &num_of_people) != 1)
printf("Was hoping for a number between 1 and 8\n" );
else
calculate_pizza_share(num_of_people);
}