【发布时间】:2021-04-04 12:24:52
【问题描述】:
所以基本上用户在一个变量中输入他们访问过多少个国家,然后我把它作为数组的大小。
之后,我使用for 循环列出所有访问过的国家/地区。但我想让我的代码更智能一点,并将and 放在最后一个国家/地区的句子末尾。
例如3国家:
You visited Japan, Korea and Canada.
^ ^^^
#include <stdio.h>
#include <cs50.h>
int main(void)
{
int number_of_p = get_int("How many countries did you visit?\n");
string countries[number_of_p];
for (int x = 0; x < number_of_p; x++)
{
countries[x] = get_string("What countries did you visit?\n");
}
printf("You visited %i countries, including: ", number_of_p);
for (int x = 0; x < number_of_p; x++)
{
printf("%s, ", countries[x]);
/* looks for last element in arrays, inserts 'and'
to make it look grammatically correct. */
if (countries[x] == number_of_p - 1 ) // ERROR HERE
{
printf(" and ");
}
}
printf(".\n");
}
我正在比较指针 (char*) 和整数错误。
char* 是什么意思?
如何访问数组中的最后一个元素?
【问题讨论】:
-
x是您的索引。这就是您要检查的内容。countries[x]是一个字符串。即if (countries[x] == number_of_p - 1 )应该是if (x == number_of_p - 1 )。 -
但我正在检查 x,如果国家 [x] == number_of_p - 1 然后打印 f。所以就像拿国家一样,它等于大小变量减1,然后用空格打印出'and'。我还有一个问题。 wtf char* 是什么意思?我使用了一个字符串而不是一个字符。还有 * 做什么,我查了一下它的意思是指针,但 char* 与此有什么关系,为什么我得到指针和 int 比较错误。请解释清楚,因为我是一个愚蠢的初学者