这是一个计算房间里人们年龄的简单程序。 我现在处于初始阶段,现在我看到我不知道哪些变量(我的意思是我在scanf之前声明的变量,然后是scanf中的占位符)用于scanf;如何选择和应用正确的变量。是否有资源可以用简单的英语解释这些问题? 这是程序:
// Ages people by a year. Arrays
#include <stdio.h>
int main (void)
{
// determine number of people
int n;
do
{
printf("Number of people in room: ");
scanf ("%i", &n);
}
while (n<1); // get the number of people in the room, pass through user
// again and again until the user gives a positive integer
// declare array in which to store everyone's age
int ages[n];
int i;
for (i = 0; i < n; i++)
{
printf("Age of person #%i: ", i + 1); // person number 1, person number 2, etc
scanf ("%d", ages[i]); // store the age in the i-th part of the array ages
}
// report everyone's age a year hence
printf("Time passes...\n\n");
for (i = 0; i < n; i++)
{
printf(" A year from now person #%i will be %i years old.\n", i + 1, ages[i] + 1);
// we add 1 year to previous age
}
}
答案 0 :(得分:2)
答案 1 :(得分:1)
scanf
需要指向某个变量的指针才能更改它的值 - 否则会获得一些不会影响实变量的副本。
这一行:
scanf ("%d", ages[i]);
取消引用ages
并返回一个整数,而不是指向整数的指针。
改变它
scanf ("%d", &ages[i]);
&
将提取ages[i]
的内存地址并将其作为指针传递给scanf