gpt4 book ai didi

c - C 函数中的简单函数

转载 作者:行者123 更新时间:2023-11-30 20:02:26 28 4
gpt4 key购买 nike

我正在做一些简单的事情,但我似乎无法让它发挥作用。

基本上,我有 main() ,它基本上显示了字符如何以两种不同的方式显示。然而,我试着让它变得有趣一点,让它循环起来。我知道我可以更轻松地做到这一点,但只是想脚踏实地。

#include <stdio.h>
/* displays code number for a character*/
char Chat(void);

int main(void)
{
char ch, gr;
printf(" please enter a character.\n");
scanf("%c", &ch);
printf("The code for %c is%d. \n", ch, ch);

Chat(void);
if (gr == 'y')

main();
else
return 0;

}
/* this function should obtain the value of gr and then send it to main() so that main can avaluate if
it should run again*/

char Chat(void)
{
char gr;
printf(" press y for again, press n for instant death");
gr = getchar();
return gr;

}

我希望我想做的事情是有意义的......而且我认为没有必要将其删除,因为我可能留下了一些错字......认真的人们。

最佳答案

一些提示:

  1. Start the function names with small letters. But that's just a convention in the most of the community.
  2. Make sure you always return something in main.
  3. Instead of calling main(); (which is dangerous) inside main, you can use a do-while loop, which is better.

    4. Passing void at Chat(void) is not valid.

  4. You are not using the return value of Chat(void) any where.
  5. else before return 0 is not needed.

  6. getchar() swallows the inputs such as \n characters that were intended to enter previous inputs.

那个吞下导致程序在一轮循环中停止。我已经更改了您的代码并添加到下面。 do-while 版本在该版本下单独给出。

代码中添加了一些 getchars 以消除一些逻辑错误,并且删除了 Chat(void) 以纠正编译器错误:

     #include <stdio.h>
/* displays code number for a character*/
char Chat(void);

int main(void)
{
char ch, gr;
printf(" please enter a character.\n");
scanf("%c", &ch);
getchar(); //swallows newline
printf("The code for %c is %d. \n", ch, ch);
gr=Chat();
if (gr == 'y')
main(); // this is not a good idea....
return 0;
}
char Chat(void)
{
char gr;
printf(" press y for again, press n for instant death");
gr = getchar();
getchar(); // swallows newline
return gr;

}

编辑:这是代码的do-while版本

#include <stdio.h>
/* displays code number for a character*/
char Chat(void);

int main(void)
{
char ch, gr;
do{
printf(" please enter a character.\n");
scanf("%c", &ch);
getchar(); //swallows newline
printf("The code for %c is %d. \n", ch, ch);
gr=Chat();
}while(gr=='y');
return 0;
}
char Chat(void)
{
char gr;
printf(" press y for again, press n for instant death");
gr = getchar();
getchar(); // swallows newline
return gr;

}

关于c - C 函数中的简单函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16990479/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com