C简介-如何在函数中通过引用传递参数? [英] C intro - How to pass a parameter by reference in function?

查看:56
本文介绍了C简介-如何在函数中通过引用传递参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从事C语言入门课程的分配,并且承担以下任务...

I'm working on my intro C course assignment and I'm tasked with the following...

  1. 为一个函数编写代码,该函数按值接收两个参数(a和b),并通过引用具有另外两个参数(c和d).所有参数都是double.
  2. 从main中,使用scanf获取两个数字,然后调用该函数,然后在printf语句中将两个返回的值显示到输出中.
  3. 该函数通过将(a/b)分配给c并将(a * b)分配给d来工作.

虽然我的知识很基础,但我相信我了解要点在主要

While my knowledge is basic, I believe I understand the gists In main

      //first and second double hold the scanf inputs
      double first;
      double second;

      //unsure here - to reference c and d as parameters in the function, do I simply declare unfilled double variables here?
      double *c;
      double *d;

   printf("Enter your first number\n");
   scanf("%f\n", &first);
   printf("Enter your second number\n");
   scanf("%d\n", &second);

   //call the function, first and second by value, &c / &d by reference - correct?
   pointerIntro(first, second, &c, &d);

对于功能...

float myFunction(double a, double b, double *c, double *d)
{
c = a/b;
d = a*b;


//printf statements
}

我很抱歉这个问题的流程很混乱,但这对我来说是过程的一部分:P

I apologize if the flow of this question is messy but its part of the process for me :P

所以,对于我的正式问题1.在main中启动两个双指针变量(* c& * d)作为函数中的引用传递是否正确?2.我可以通过说& c/& d来调用带有引用指针的函数吗?3.对此质疑还有其他批评吗?

So, for my formal questions 1. is it correct to initiate two double pointer variables (*c & *d) in main to be passed as reference in the function? 2. Am I right to call the function with the reference pointers by saying &c / &d? 3. Any other critiques of this questioning?

推荐答案

  1. 这是完全有效的.您可以初始化并传递任意数量的指针变量及其引用.

  1. It is perfectly valid. You can initialize and pass any number of pointer variables with their reference.

这也是有效的.当您传递变量地址时,应将其存储到指针中

This is also valid..when you pass the variable address, you should store it into a pointers

您必须对代码进行一些更改,您可以直接分配 a/b和a * b 指针变量 * c&* d 然后,您必须使用%lf 格式参数读取双精度数字.

you have to do some changes in your code, You can assign directly a/b and a*b pointer variables *c & *d Then you have to read double number with %lf format argument.

#include <stdio.h>
#include <string.h>

void myFunction(double a, double b, double *c, double *d)
{
*c = a/b;   //change
*d = a*b;   //change
printf("%lf %lf",*c,*d);
return;
//printf statements
}



int main()
{
//first and second double hold the scanf inputs
double first;
double second;

//unsure here - to reference c and d as parameters in the function, do I simply declare unfilled double variables here?
double *c;
double *d;

printf("Enter your first number\n");
scanf("%lf", &first);   //change
printf("Enter your second number\n");
scanf("%lf", &second);  //change

//call the function, first and second by value, &c / &d by reference - correct?
myFunction(first, second, &c,&d);
}

这篇关于C简介-如何在函数中通过引用传递参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆