如何通过使用指针将输入函数中的2 int,1 float变量输入传递给main函数?

时间:2019-04-28 13:48:58

标签: c pointers

我正在制作票据计算器,我需要在输入函数中输入2个整数和1个实数,并且我需要将这3个数字转换为月份函数,以使用输入函数提供的3个数字来计算票据。

...
float input(int*,int*,float*);
void months(int, int, int, int, float, float,int,int,float);
...
int main()
{
  ...
  int x1,y1;
  float z1;
  ...
  int *x= &x1;
  int *y= &y1;

  float *z= &z1;
}

float input(int*x,int*y,float*z)
{
  ...
  printf("\nInput your usages of voice : ");
  scanf_s("%d", &x);
  printf("Input your usages of text : ");
  scanf_s("%d", &y);
  printf("Input your usages of data : ");
  scanf_s("%f", &z);
  ...
}

void months(...,int*x,int*y,float*z)
{
  ...
}

我希望如果我输入x,y,z 150,100,2.11然后 150,100,2.11也可以放在月份函数中,但是在月份函数x,y,z中则是垃圾值。

1 个答案:

答案 0 :(得分:1)

您已经在 input 中的参数中获取了变量的地址,因此请替换

scanf_s("%d", &x);
...
scanf_s("%d", &y);
...
scanf_s("%f", &z);

作者

scanf_s("%d", x);
...
scanf_s("%d", y);
...
scanf_s("%f", z);

除此之外,您不需要在 main 中使用指针变量,可以替换

int x1,y1;
float z1;
...
int *x= &x1;
int *y= &y1;
float *z= &z1;
...
float v = input(x,y,z); /* added */

作者

int x1,y1;
float z1;
...
float v = input(&x1,&x2,&z1); /* added */

如果我对 month 函数有很好的了解,您也可以直接提供 x1,y1,z1 而不是其地址。请注意,声明void months(int, int, int, int, float, float,int,int,float);与定义不匹配,甚至部分void months(...,int*x,int*y,float*z)

我还建议您检查scanf_s的结果,以确保用户输入了有效的输入


如果我考虑到我的评论而更改了您的代码:

#include <stdio.h>

int input(int*,int*,float*);
float months(int, int, float);

int main()
{
  int x1,y1;
  float z1;

  if (input(&x1, &y1, &z1))
    printf("%g\n", months(x1, y1, z1));

  return 0;
}

/* return 0 if an input is erronned */
int input(int*x,int*y,float*z)
{
  printf("\nInput your usages of voice : ");
  if (scanf_s("%d", x) != 1)
    return 0;
  printf("Input your usages of text : ");
  if (scanf_s("%d", y) != 1)
    return 0;
  printf("Input your usages of data : ");
  if (scanf_s("%f", z) != 1)
    return 0;
  return 1;
}

/* return the bill */
float months(int x,int y,float z)
{
  return x + 1.2 * y + z *100; /* just to return a value */
}

编译和执行:

pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra i.c
pi@raspberrypi:/tmp $ ./a.out 

Input your usages of voice : 150
Input your usages of text : 100
Input your usages of data : 2.11
481