【问题标题】:How can I call with a int function in main function?如何在主函数中使用 int 函数调用?
【发布时间】:2018-10-04 08:46:36
【问题描述】:

我需要在函数 main > my_isneg 中插入一些东西来调用 my_isneg 函数。我该怎么做?

#include <unistd.h>
void my_putchar (char c)
{
    write (1, &c, 1);
}
int my_isneg (int n)
{

    if (n < 0) {
        my_putchar (78); }
    else {
        my_putchar (80);
    }
}

int main (void)
{
    my_isneg();
}

【问题讨论】:

  • 你的函数名不是my_inseg,而是my_isneg,它执行my_putchar 的字母N(负)或P(正)。 my_putchar 是什么,你想用它做什么?
  • 欢迎来到stackoverflow。请阅读:How to Ask。完全不清楚你在问什么。 my_isneg 应该做什么?您在没有参数的情况下调用my_isneg(),这是错误且毫无意义的。数字 78 和 80 代表什么?
  • 78 和 80 用于 ASCII 表,我想要那个打印,如果执行告诉我,如果数字是正打印 P,如果负 N
  • @Jonathan 而不是查找 ASCII 表并编写 7880 让 C 编译器为您完成工作并编写 'N''P'
  • @Jabberwocky 但是如何在 main 中使用数字,就在你执行(./a.out 5)时,我不怎么调用函数 main >my_isneg 到 my_isneg

标签: c linux


【解决方案1】:

有点不清楚你在问什么,但也许你想要这个:

...
// print 'N' 1 if the number n is strictly negative, print 'P' otherwise
int my_isneg(int n)
{
  if (n < 0) {
    my_putchar('N');  // use 'N' instead of 80 (it's more readable)
  }
  else {
    my_putchar('P');  // use 'P' instead of 80
  }
}

int main(void)
{
  my_isneg(-1);
  my_isneg(1);
  my_isneg(2);
}

输出

NPP

或者也许这个,更接近名称my_isneg

...
// return 1 if the number n is strictly negative
int my_isneg(int n)
{
  return n < 0;
}

int main(void)
{
  if (my_isneg(-1))
    my_putchar('N');
  else
    my_putchar('P');

  if (my_isneg(1))
    my_putchar('N');
  else
    my_putchar('P');
}

输出

NP

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    • 2019-03-04
    • 1970-01-01
    相关资源
    最近更新 更多