简单的if / else语句错误

时间:2013-10-17 11:49:58

标签: c if-statement

所以我有这个程序将F转换为C,反之亦然,我想修改它,使其不接受低于绝对零度的温度作为有效输入。出于某种原因,我在这一行遇到错误:

else if (Celsius < -273.15)
   {
   printf("ERROR! The temperature is below absolute zero.");
   }

这是我的全部代码:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

float c2f(float);
float f2c(float);

float Fahrenheit,Celsius;

int main(int argc, char *argv[])
{

/** 
 * Check for the expected number of arguments (3)
 * (0) program name
 * (1) flag
 * (2) temperature
 */
if (argc!=3)
{
    printf("Incorrect number of arguments\n");
    exit(0);
}

if (!strcmp(argv[1], "toF"))
{
   // convert the string into a floating number
   char *check;
   float Celsius = strtod(argv[2], &check);

   else if (Celsius < -273.15)
   {
   printf("ERROR! The temperature is below absolute zero.");
   }

// process from celsius to fahrenheit
   Fahrenheit = c2f(Celsius);
   printf("%5.2f°C = %5.2f°F\n",Celsius, Fahrenheit);
}   
else if (!strcmp(argv[1], "toC"))
{
   // convert the string into a floating number
   char *check;
   float Fahrenheit = strtod(argv[2], &check);

   // process from fahrenheit to celsius
   Celsius = f2c(Fahrenheit);
   printf("%5.2f°F = %5.2f°C\n", Fahrenheit, Celsius);
}

else 
{

else
   printf("Invalid flag\n");
} // main


float c2f(float c)
{
  return 32 + (c * (180.0 / 100.0)); 
} 

float f2c(float f)
{
  return (100.0 / 180.0) * (f - 32);
}

这些是我因为那条线而得到的错误:

part4.c:在函数'main'中:

part4.c:31:错误:在'else'之前预期'}'

part4.c:29:警告:未使用的变量'Celsius'

part4.c:顶级:

part4.c:40:错误:预期标识符或'('在'else'之前

part4.c:51:错误:预期标识符或'('在'else'之前

make: * [part4]错误1

对此有何看法?

谢谢!

1 个答案:

答案 0 :(得分:2)

这部分是问题所在:

else if (Celsius < -273.15)
{
   printf("ERROR! The temperature is below absolute zero.");
}

将其更改为:

if (Celsius < -273.15)
{
    printf("ERROR! The temperature is below absolute zero.");
}

还有:

else 
{

//else  --> remove this
   printf("Invalid flag\n");
}-->  Add a brace
} // main

语法更正代码 - http://ideone.com/Ej9iJ8