2016-02-07 100 views
0

我有两个代码问题,第一个问题是程序要我输入两次号码,第二个问题是程序结束后立即关闭程序。 我试图用getchar()声明来阻止它,但它似乎并不奏效。函数问题

#include <stdio.h> 

int square(int);  /*function prototype*/ 

main() 
{ 
    int x;    /*defining the function*/ 
    printf("Enter your number\n"); 
    scanf_s("%d \n", &x);  /*reading the users input*/ 
    printf("Your new answer is %d \n", square(x)); /*calling the function*/ 
    getchar(); 
    getchar(); 

} 

int square(y) /*actual function*/ 
{ 
    return y * y; 

} 
+0

如果你使用'conio.h'库,它效果更好,你不需要担心这个:) – bahjat

回答

0

我会建议使用scanf("%d", &x);来读取您的号码。你的问题是你的论点看起来像这样:"%d \n"所以程序希望你输入你的号码AND \ n。这样,你说你想如何看待你的x,在你的情况下,它期望它是一个数值,空格和行尾。

至于关闭的一个,使用getch();。对于此功能,您需要像使用stdio一样包含conio.h,意思是:#include <conio.h>

+0

谢谢你解决了这一切。 从现在起我将使用'conio.h'库。我还会找出两个图书馆之间的区别。非常感谢回答我的问题,非常感谢 – bahjat

+0

如果这有帮助,请将我的答案标记为解决方案。 –

+2

@bahjat请注意,'conio.h'是非标准的,并不适用于所有平台。 –

1

通过改变

scanf_s("%d \n", &x); 

scanf_s("%d", &x); 

解决这个问题的问题是,在scanf insructs scanf格式字符串空白字符(空格,换行等)来扫描并丢弃任何空白字符的数量,如果有的话,直到第一个非空白字符。


至于与getchar()问题,请更换第一getchar()有:

int c; 
while((c = getchar()) != '\n' && c != EOF); 

这将扫描并放弃一切,直到\nEOF


此外,变化

main() 

int main(void) 

int square(y) 

int square(int y) 
+0

如果你在Linux下工作,你不需要'int main(void)'。你可以使用'void main(void)'或简单的'main(){..}'。 –

+1

@SimplyMe根据最新的标准,'main'的有效形式是'int main(void)'和'int main(int argc,char ** argv)' –

+1

@SimplyMe Linux或不, '不是标准C.'main'具有'int'的返回类型.http://stackoverflow.com/q/204476/2072269,http:// stackoverflow。com/a/4207223/2072269 – muru