如何定义一个从用户那里获取输入并将其存储到程序中进一步使用的变量的函数?

How to define a function that takes input from user and stores that to a variable which is further used in the program?

我正在编写以下代码,但是当我输入并尝试执行时,结果总是根据 FALSE 情况,即使 true 的条件证明是正确的。 例如:如果我输入 h=2,它遵循一个错误的案例,如果我输入 h=34,那么它也遵循一个错误的案例。 请告诉我我犯的错误。

#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
int input(int a);
void pyramid(void);
int h;
int main(void) {
  input(h);
  if(h>0 && h<9) {
       pyramid();
    }
  else {
       do {
          input(h);
       } while(h>8 || h<1);
       pyramid();
  }
}

void pyramid(void) {
  printf("sfsdfsf");
}   

int input(int a) {
  printf("Height: ");
  scanf("%d", &a);
  return(a);
}

问题出在您调用 input 时:input(h);h 按值(或副本)传递,这意味着函数中发生的任何事情对 h 都是不可见的。因此:

要么你使用函数的return值:

h = input(h);

在那种情况下,将值传递给函数有点奇怪...... 因此,首选技巧可能是:

h = input();

int input() {
  int a;
  printf("Height: ");
  scanf("%d", &a);
  return a;
}

这更清楚地表达了这样一个事实,即您调用的函数使 return 您成为一个值(这个函数真正做的事情在调用点并不有趣)。

要么你传递变量的地址:

input(&h);

void input(int *a) {
  printf("Height: ");
  scanf("%d", a);
}

这表示函数采用它将修改的变量的地址。

假设你想把朋友的phone号写到纸上,有两种解法:

  1. 让他把它写在他拥有的纸上,并在 return 中给了你纸。
  2. 让他写在你给他的纸上。