c++ - 在不使用单个 if 的情况下执行某些语句

标签 c++ c

我正在尝试解决流动问题:

给你一个名为 n 的整数。
如果 n 为正数,则打印 '+',
如果 n 为负数,则打印 '-',
如果 n 为零,则打印“0”。

在不使用单个 if 的情况下编写 c\c++ 解决方案!

我写了这段代码:

int n;
scanf("%d", &n);

! n >> (sizeof(n) - 1) && printf("-") || return 0;
n > 0 && prtintf("+") || return 0;
printf("0");
retuen 0;

但我收到错误:第 3 行和第 4 行的“返回”之前需要主表达式。 我该如何更改此代码以使其正常工作!

p.s:使用? : 算作作弊!

最佳答案

是的,这是可行的(有一些限制)。

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

// Assuming 2s-complement numbers
// and an understanding compiler
// Some checks omitted!

int main(int argc, char **argv)
{
  int input;
  unsigned int itmp;
  int size;
  int sign, sin, sout;
  char out[3] = { '0', '+', '-' };


  if (argc != 2) {
    fprintf(stderr, "Usage: %s integer\n", argv[0]);
    exit(EXIT_FAILURE);
  }
  // TODO: use strtol and check input!
  input = atoi(argv[1]);

  size = sizeof(int) * CHAR_BIT;
  itmp = (unsigned int) input;

  sin = itmp >> (size - 1);
  sign = sin ^ 1;

  // now "sign" is either 0 (negative) or 1 (positive)
  // but we need 1 (negative) and -1 (positive)
  // 0 * -2 + 1 = 1
  // 1 * -2 + 1 = -1

  sign = sign * -2 + 1;

  // Now we can do
  // in   sign   out   sin   sout
  // -x *   1 = -x ->   1  +  1  =  2
  // +x *  -1 = -x ->   0  +  1  =  1
  //  0 *  -1 =  0 ->   0  +  0  =  0

  itmp = itmp * sign;
  sout = itmp >> (size - 1);

  sign = sin + sout;

  printf("Input: %c\n", out[(size_t) sign]);

  exit(EXIT_SUCCESS);
}

没有条件表达式,既不使用 if 显式使用,也不使用 whilefor 隐式使用,也不使用快捷方式 ...? ...:....

关于c++ - 在不使用单个 if 的情况下执行某些语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40821056/

相关文章:

c++ - 初始化数组的更好方法

c++ - 将 C++ 数组传递给 Fortran 子例程导致 nan 值出现在结果中

c - 按位循环遍历大数据 block 的最快方法是什么

c - linux线程和内存/变量

c - 如何在 C 中将字符串添加到 PUNICODE_STRING 的末尾

c - C 程序中涉及指针变量的访问冲突?

c++ - 为什么在 main() 中声明的指针没有改变?

c++ - 在这个简单的例子中安全地调用 new 的最佳方法是什么?

C++ 使用 Map 中的参数调用函数

c - 找出左子右兄弟树中某个高度处有多少个节点?