2016-01-24 68 views
-3

所以我刚开始用发问反应 学习C语言编程和我决定让我的程序修炼到最终用户说出来应用开关,它关闭?

我首先应用如 - else语句,以便程序根据人的年龄作出反应。 然后,当我到达什么是你最喜欢的颜色部分与开关语句它会刚刚按下任何按钮时关闭。

我的代码:

#include <stdio.h> 
#include <conio.h> 
#include <dos.h> 
#include <ctype.h> 

main() 
{ 

char name[25], c; 
int a; 
clrscr(); 

printf("Hello, whats your name? \n"); 
scanf("%s",name); 
printf("nice to meet you %s!!!\n"); 

printf("Whats your age?"); 
scanf("%d",&a"); 
    { 
     if((a <= 21) && (a >= 0)) 
     printf("Young!\n"); 

     else if((a <= 100) && (a >= 22)) 
     printf("old!\n"); 

     else 
     printf("that's not an age!\n"); 
    } 

printf("whats your favorite color? \n"); //this is where the program stops// 
scanf("%c",&c); 
    switch(tolower(c)){ 
    case 'r':printf("Fiery!");break; 
    case 'o':printf("oranggerrr!!");break; 
    . 
    . //basically applied the whole rainbow and put some reactions// 
    . 

getch(); 
return 0; 
} 
+0

我不确定我是否理解问题所在。 –

+1

这看起来像他/她在问为什么它的工作。写在评论 – Shial

+0

对不起,我刚刚编辑。^- ^ – Mirisu

回答

0

好了,我编程序的在线here,做一些改变,因为你给的程序只有在旧的Turbo C.

我整理汇总下面的程序:

#include <stdio.h> 
//#include <conio.h> 
//#include <dos.h> 
#include <ctype.h> 

main() 
{ 

char name[25], c; 
int a; 
//clrscr(); 

printf("Hello, whats your name? \n"); 
scanf("%s",name); //still dont get why it worked without the "&"// 
printf("nice to meet you %s!!!\n"); 

printf("Whats your age?"); 
scanf("%d",&a); 
    { 
     if((a <= 21) && (a >= 0)) 
     printf("Young!\n"); 

     else if((a <= 100) && (a >= 22)) 
     printf("old!\n"); 

     else 
     printf("that's not an age!\n"); 
    } 

printf("whats your favorite color? \n"); //this is where the program stops// 
scanf("%c",&c); 
    switch(c){ 
    case 'r':printf("Fiery!");break; 
    case 'o':printf("oranggerrr!!");break; 
    // . 
    //. //basically applied the whole rainbow and put some reactions// 
    //. 
    } 

getchar(); 
return 0; 
} 

好吧,所以当我执行它时,我得到了一个分段错误,因为这条线:

printf ("nice to meet you %s!!!\n"); 

printf ("nice to meet you %s!!!\n", name); 

然后一切都工作正常。

现在您的疑问:

  • scanf ("%s", name); 做是因为名字是一个字符数组,数组的名字就是数组在等于第一个元素的地址。检查this评论。此外,你可以看到这个问题。

改进:

  • 变化scanf ("%c", &c);scanf (" %c", &c);

注:我不能准确地再现您的问题,因为我不具备的Turbo C.另外,也许你的程序崩溃是因为tolower。请注意,tolower返回已更改的字符,因此您必须执行以下操作:c = tolower (c);