【发布时间】:2015-01-28 09:23:58
【问题描述】:
这是我的代码:
我的问题是我想用一个 while 循环来循环 switch 语句,这取决于 char 响应得到什么(在底部)。
我尝试将整个 switch 语句放在一个 do while 循环中(失败了)。
无论如何,我是这门语言的新手,我想尝试制作一个复杂的程序。
#include <stdio.h>
#include <stdlib.h>
#define LINE "____________________"
#define TITLE "Tempature Converter"
#define NAME "Jose Meza II"
char scale, response;
float temp, celTemp, farTemp, kelTemp;
int main() {
printf("\n \t %s \n \t %s \n", LINE, TITLE );
printf("\t by %s \n \t %s \n\n", NAME, LINE );
printf("Enter C for Celsius, F for Fahrenheit, or K for Kelvin: ");
scanf("%c", &scale);
printf("Tempature value: ");
scanf("%f", &temp);
switch (scale)
{
case ('c'): /* convert to Fahrenheit and Kelvin */
{
farTemp = (temp * 9 / 5) + 32;
kelTemp = temp + 273.15;
printf("Fahrenheit = %.2f\n", farTemp);
printf("Kelvin = %.2f\n\n", kelTemp);
break;
} /* end case 'c' */
case ('f'): /* convert to Celsius and Kelvin */
{
celTemp = (temp - 32) * 5 / 9;
kelTemp = (temp - 32) * 5 / 9 + 273.15;
printf ("Celsius = %.2f\n", celTemp);
printf ("Kelvin = %.2f\n\n", kelTemp);
break;
} /* end case 'f' */
case ('k'): /* convert to Celsius and Fahrenheit */
{
celTemp = temp - 273.15;
farTemp = (temp - 273.15) * 9 /5 + 32;
printf("Celsius = %.2f\n", celTemp);
printf("Fahrenheit = %.2f\n\n", farTemp);
break;
} /* end case 'k' */
default: exit(0); /* no valid temperature scale was given, exit program */
} /* end switch */
printf("Enter in C to Continue, or S to stop: ");
scanf(" %c", &response);
return 0;
}
我能做什么?
我试过了:
do
{
printf("Enter C for Celsius, F for Fahrenheit, or K for Kelvin: ");
scanf("%c", &scale);
printf("Tempature value: ");
scanf("%f", &temp);
switch (scale)
{
case ('c'): /* convert to Fahrenheit and Kelvin */
{
farTemp = (temp * 9 / 5) + 32;
kelTemp = temp + 273.15;
printf("Fahrenheit = %.2f\n", farTemp);
printf("Kelvin = %.2f\n\n", kelTemp);
break;
} /* end case 'c' */
case ('f'): /* convert to Celsius and Kelvin */
{
celTemp = (temp - 32) * 5 / 9;
kelTemp = (temp - 32) * 5 / 9 + 273.15;
printf ("Celsius = %.2f\n", celTemp);
printf ("Kelvin = %.2f\n\n", kelTemp);
break;
} /* end case 'f' */
case ('k'): /* convert to Celsius and Fahrenheit */
{
celTemp = temp - 273.15;
farTemp = (temp - 273.15) * 9 /5 + 32;
printf("Celsius = %.2f\n", celTemp);
printf("Fahrenheit = %.2f\n\n", farTemp);
break;
} /* end case 'k' */
default: exit(0); /* no valid temperature scale was given, exit program */
} /* end switch */
printf("Enter in C to Continue, or S to stop: ");
scanf(" %c", &response);
}
while(response == 'c');
【问题讨论】:
-
一个建议:尽量让程序更简单。不是更复杂。
-
这是你的作业吗?您究竟尝试过什么?向我展示你尝试过的 do-while 循环,我们可以看到你可能做错了什么。
-
这有什么好玩的(我 14 岁)
-
所以没有。不是我的作业
标签: c loops switch-statement