Прохождение простой программы на C
У меня есть этот вопрос, чтобы пройти и показать вывод при запуске этой программы. Единственное, чего я не понимаю, так это того, как выяснилось, что f равно четырем или вообще найдено. Я знаю, что правильный ответ
7 сокол 3
9 РК 4
_
Я просто не знаю, как они нашли значение f, равное 4, когда у меня есть, я могу делать все остальное нормально
#include <stdio.h>
#include <string.h>
void falcon(int f);
char a[20];
int main() {
int i, j;
a[3] = 'G';
a[1] = 'K';
i = 3 + 2 * 3;
j = 4;
a[2] = 'Y';
falcon(j);
printf("%d %s %d\n", i, a, j);
}
void falcon(int f) {
int j;
j = 11 % f;
printf("%d falcon %d\n", f+3, j);
a[2] = '\0';
a[0] = 'R';
}
2 ответа
Решение
Давайте пройдемся по программе вместе (с вырезанными неуместными битами).
#include <stdio.h>
#include <string.h>
void falcon(int f);
char a[20];
int main() {
int i, j;
j = 4;
falcon(j); // in other words, falcon(4). Now, let's go down to the
// falcon function where the first argument is 4.
printf("%d %s %d\n", i, a, j);
}
void falcon(int f) { // Except here we see that in this function,
// the first argument is referred to by 'f',
// which, as we saw, is 4.
int j;
j = 11 % f; // here, j is equal to the remainder of 11 divided by
// f, which is 4.
printf("%d falcon %d\n", f+3, j);
}
Теперь вы видите, почему код не должен иметь i
с и j
s для имен переменных за исключением, вероятно, циклов.
В любом случае,
char a[20];
на вершине говорит, что a
является глобально объявленным символьным массивом
int main()
{
int i, j; // declares two local stack variables, i and j
a[3] = 'G'; // sets 4th location in 'a'(remember, arrays start at 0) to 'G'{useless}
a[1] = 'K'; // sets 2nd location in 'a' array to 'K'
i = 3 + 2 * 3; // i is now 9 {remember, multiplication before addition}
j = 4; // j is now 4
a[2] = 'Y'; // a[2] is now 'Y'
falcon(j); // call to falcon, with argument 4, explained next
printf("%d %s %d\n", i, a, j); // prints "9 RK 4"
//return 0; -- this should be added as part of 'good' practices
}
void falcon(int f)
{
// from main(), the value of 'f' is 4
int j; // declares a local variable called 'j'
j = 11 % f; // j = 11 % 4 = 3
printf("%d falcon %d\n", f+3, j); // prints 7 falcon 3
a[2] = '\0'; // a[2] contains null terminating character, overwrites 'Y'.
a[0] = 'R'; // sets a[0] to 'R'. At this moment, printf("%s",a); must yield "RK"
}