所以,我刚刚开始(原谅我的诺言),而且我正在使用Xcode在Mac上使用C程序。它基本上只是一个scanf(),然后是大量产生预定输出的if语句。我已经写过它,这样Xcode就可以编译它而不会被惹恼,但是我得到了一个奇怪的" Fix-it"我尝试运行它时出错并且没有输出。
char planet[9];
printf("Input the name of a planet\n");
scanf("%c", &planet);
if (planet == "Earth")
{printf("Earth is 150 million kilometers away from the sun");}
if (planet == "Mars")
{printf("Mars is 220 million kilometers away from the sun");}
if (planet == ("Mercury"))
{printf("Mercury is 57 million kilometers from the sun");}
if (planet == ("Venus"))
{printf("Venus is 108 million kilometers from the sun");}
if (planet == ("Jupiter"))
{printf("Jupiter is 779 million kilometers from the sun");}
if (planet == ("Saturn"))
{printf("Saturn is 1.73 billion kilometers from the sun");}
if (planet == ("Uranus"))
{printf ("Uranus (haha) is 2.88 billion kilometers from the sun");}
if (planet == ("Neptune"))
{printf("Neptune is 4.5 billion kilometers from the sun");}
return 0;
是代码本身,但我无法使其工作。
这里也是Xcode项目的链接。
答案 0 :(得分:4)
planet
的地址永远不会等于任何字符串文字的地址。您需要使用strcmp
来比较字符串的内容,而不是比较它们的地址。
答案 1 :(得分:4)
使用strcmp
:
if (strcmp(planet, "Earth") == 0) {
...
}
此外,%c
扫描一个字符,而不是字符串。您需要使用%s
来扫描字符串。并且您需要指定最大长度以避免溢出缓冲区:
scanf("%8s", planet);
最大长度比缓冲区大小小1,因为你必须为NUL终结器留出空间。
答案 2 :(得分:0)
你将星球的地址与那些字符串文字的地址进行比较......所以地址不一样。您应该比较两个字符串的内容,如下所示:
首先包括<string.h>
,并在每个if语句中写这样的
if(!strcmp ( planet,"Earth" ))
由于无法直接比较c字符串,因此需要使用strcmp函数。
strcmp功能
int strcmp ( const char * str1, const char * str2 );
此函数比较两个字符串,返回值为:
a)零值表示两个字符串相等。
b)大于零的值表示第一个不匹配的字符在str1中的值大于在str2中的值;并且
c)小于零的值表示相反。