所以这是我的代码:
我的问题是我想用一个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');
答案 0 :(得分:2)
最常见的方法是使用 do-while
循环。进行以下更改
编辑后,问题似乎是
scanf("%c", &scale);
你需要在%c
之前有一个空格,比如
scanf(" %c", &scale);
最后在\n
之后避免 ENTER [C
]。