C代码中if&switch语句中的异常输出

我无法弄清楚为什么以下任何一个代码都无法按预期运行。两者都编译成执行文件。

输出:

a.out  , prints 1, expected "no value"
a.out 1, prints 2, expected 1 
a.out 2, prints 2, expected 2

使用案例:

void main(int in)
{
 int a = in ;
 printf("In function if\n");
 if ( in == 1 )
   printf("1\n");
 else
   if ( in == 2)
     printf("2\n");
   else
     printf("wrong value\n");
}

使用开关:

void main(int in)
{
  switch( in )
    {
    case  1: printf("1\n");                 break;
    case  2: printf("2\n");                 break;
    default: printf("wrong value\n"); break;
    }
};

我正在尝试在C代码中获得以下LISP功能:

(cond ((= in 1) 1)
      ((= in 2) 2)
      (t        nil))

谢谢您的帮助。

穆孔达

main不接受来自命令行的输入作为直接参数,您将在其中获得参数计数,即1是否没有参数,以及2是否有一个参数,这会导致奇怪的行为。

main应该定义为int main( int argc, char *argv[] )或类似的名称。要获取输入,您需要首先通过测试argc(参数计数,加上可执行路径的一个)来检查它是否存在,然后转换argv[1]为整数。atoi可用于将字符串转换为整数。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章