【发布时间】:2014-09-14 09:30:54
【问题描述】:
我正在编写一个程序,它输入三个数字,然后计算一些不同的东西(每个东西都必须是它自己的函数)。程序开始告诉用户他们的选择并等待他们的输入。在任何情况下执行后,程序将再次打印菜单,但它将使用默认情况,然后它将打印菜单并要求输入。任何帮助将不胜感激。
#include <stdio.h>
#include <stdlib.h>
void greeting() {
printf("Welcome to Dr. Computer's Mathatorium \n"); // this is a seperate function just because
printf("Remember to use capital letters when selecting \n");
}
//This getNum function is used to the get the number
int getNum ()
{
int a;
printf("Enter your first integer:"); //tells user to input number
scanf("%i", &a); //input
return a;
}
// gets the sum of the numbers
int getSum (int f, int g, int h)
{
return (f + g + h);
}
// gets the sum of the numbers
int getPro (int f, int g, int h)
{
return (f * g * h);
}
// gets the sum of the numbers
int getAvg (int f, int g, int h)
{
return (f * g * h)/3;
}
// gets the sum of the numbers
int getLow (int f, int g, int h)
{
return (f + g + h); //NEEDS ADJUSTING
}
main()
{
int first, second, third, sum, pro, avg, low;
char choice;
greeting ();
do {
printf("Main Menu\n");
printf("A) Get Three Integers\n");
printf("B) Display the Sum\n");
printf("C) Display the Product\n");
printf("D) Display the Average\n");
printf("E) Display the lowest\n");
printf("F) Quit\n");
scanf("%c", &choice);
//here comes the switches to route the choices
switch(choice){
case 'A':
first = getNum ();
second = getNum ();
third = getNum ();
printf("first is: %i\n", first);
printf("second is: %i\n", second);
printf("third is: %i\n", third);
break;
case 'B':
sum = getSum (first, second, third);
printf("sum is: %i\n", sum);
break;
case 'C':
pro = getPro (first, second, third);
printf("product is: %i\n", pro);
break;
case 'D':
avg = getAvg (first, second, third);
printf("average is: %i\n", avg);
break;
case 'E':
avg = getAvg (first, second, third); //NOT DONE YET
printf("average is: %i\n", avg); //REMEMBER TO FIX
break;
default:
printf("INVALID CHOICE!\n");
break;
}
} while (choice != 'F');
return 0;
}
【问题讨论】:
-
问题不太清楚。你能重新定义你的问题吗?
-
do{...}while()实际上执行循环然后检查条件。可以找while(){..} -
当您输入“A”并按换行符时,终端会发送两个字符:“A”和“\n”(换行符)。换行符可能会导致 switch 的第二次执行。只需忽略换行符。
-
你真的应该完全避免使用
scanf。 c-faq.com/stdio/scanfprobs.html -
请不要编辑您的问题以添加“已修复”或“已解决”。 Stack Overflow 的方法是将答案标记为已接受(如果您自己找到答案,您甚至可以标记自己的答案)。请拨打Friendly Introductory Welcome To Stack Overflow Tour。
标签: c switch-statement default