2013-10-08 156 views
-1

好吧,所以我必须创建一个天气程序,当我尝试运行代码时,我没有任何错误,但它只会打印“输入起始温度”和“输入结束温度”。但它不会让我输入数据。有什么我需要改变?我知道我还没有完成代码,但我只想在继续执行其他代码之前测试输入。谢谢您的帮助!为什么printf工作,但scanf不是?

#include <stdio.h> 
int main(int argc, char **argv) 
{ 
    float celcius, fahrenheit, kelvin, ending, interval; 
    int c, f, k, temp; 

    printf("which temperature is being input? (C,F,K) "); 
    scanf("%d", &temp); 
    if (temp == c) 
    { 
     printf("enter a starting temperature"); 
     scanf("%f", &celcius); 
     printf("enter an ending temperature"); 
     scanf("%f", &ending); 
     fahrenheit = celcius * 9/5 + 32; 
     kelvin = celcius + 273.15; 
    } 
    if (temp == f) 
    { 
     printf("enter a starting temperature"); 
     scanf("%f", &fahrenheit); 
     celcius = fahrenheit - 32 * 5/9; 
     kelvin = fahrenheit - 32 * 5/9 + 273.15; 
     printf("enter an ending temperature"); 
     scanf("%f", &ending); 
     if (temp == k) 
     { 
     } 
     printf("enter a starting temperature"); 
     scanf("%f", &kelvin); 
     fahrenheit = kelvin - 273 * 1.8 + 32; 
     celcius = kelvin - 273.15; 
     printf("enter an ending temperature"); 
     scanf("%f", &ending); 
    } 
} 
+0

由于用户输入数据后的'\ n',我通常在* scanf()格式字符串中至少在第一个IIRC之后有一个空格。 – technosaurus

+0

查看'fgets'函数,你可以用它代替'scanf' – jev

回答

3

此:

if (temp == c) 

temp新近读取值进行比较,以在未初始化的变量的c未定义的值。这是未定义的行为。

你可能是指

if (temp == 'c') 

进行比较的一个字符,但你还需要:

char temp; 
if (scanf("%c", &temp) == 1) 
{ 
    if (temp == 'c') 
    { 
    /* more code here */ 
    } 
} 

注意检查scanf()返回值有助于使程序更健壮,避免进一步使用未初始化的值(如果scanf()未能读取某些内容,则不应读取目标变量,因为它不会被写入)。

+0

'c'肯定有帮助,你的代码帮了我很多!但是,为什么添加“== 1”?那有什么意义呢?指出它是否属实? –

+0

@LewisM。 - RTFM –

0
if (temp == c) 

您与

同为

if (temp == f) 

然后每一件事情将是工作的罚款C的初始化值进行比较温度,使之更加人性化,把一个“\ n “在printf中的

这样,

printf("enter a starting temperature \n"); 
0

这里:

printf("which temperature is being input? (C,F,K) "); 
scanf("%d", &temp); 

你问要输入的字符,但你尝试扫描的int。这将甩掉你所有的scanf()电话。

0

您的变量temp被声明为一个整数。事实上,scanf()想要读取一个整数(%d),但会得到一个字符。 因此,您将temp读为char。 此外,您可以使用的

9.0/5.0 

代替

9/5 

此外,使用switch语句会增加可读性。

相关问题