c - 按值传递变量,printf 不显示正确的结果
问题描述
我是一名大学生,在我的一个训练 c 编程的练习中,我遇到了打印功能错误。我使用了很棒的 CLION,但现在转到 VS Code,因为老师说它在专业环境中使用最多。你对此有什么想法?!
主文件
#include <stdio.h>
#include "complex.h"
int main (){
Complex x;
inputNmbr(x);
printNmbr(x);
return 0;
}
复杂的.h
#include <stdio.h>
typedef struct{
float r,i;
}Complex;
Complex inputNmbr(Complex x){
printf("Input an imaginary number (R +/- I):\n");
scanf("%f %f", &x.r, &x.i);
return x;
}
void printNmbr (Complex x){
printf("Imaginary number: %.2f +/- %.2f\n", x.r, x.i);
}
终端
aluno@aluno-VirtualBox:~/Desktop/Programação por objetos/P1/EX2$ ./main\
Input an imaginary number (R +/- I):
1 2
Imaginary number: 0.00 +/- 0.00
所以 printf 函数总是显示 0 0 我不明白这个错误的来源。
PS 在受到关于 C/C++ 标签的攻击后,我发布了练习(我放置两个标签的原因与此有关):
Write a module in C that allows working with complex numbers.
Create the files complex.h and complex.cpp where you should implement the following functionalities:
The definition of data structure (Complex) to represent a complex number
(r, i);
A function that reads a complex number;
A function that writes a complex number in the format: #.#+/-#.#i (where +/- depends on the sign of the imaginary part);
A function for each of the following operations:
Addition: a+bi+c+di=(a+c)+(b+d)i
Subtraction: a+bi-c+di=(a-c)+(b-d)i
Multiplication: (a+bi)*(c+di)=(ac-bd)+(bc+ad)i
Division:
(a+bi) / (c+di)=((ac+bd)/(c^2+d^2))+((bc-ad)/(c^2+d^2))i
解决方案
我没有完成你所有的执行,但是,你不正确的问题printf
是你的结构变量 x 是“按值”传递给函数的inputNmbr
。这意味着在调用它时,会创建一个变量的副本并将其放入函数堆栈中,即使您修改了函数内部的值,修改也不会反映在原始变量中。
解决方案可以是更改inputNmbr
函数的输入参数,使其成为指针。例如:
void inputNmbr(Complex * x){
printf("Input an imaginary number (R +/- I):\n");
scanf("%f %f", &(x->r), &(x->i));
}
在这种情况下,你的主要将是:
int main (){
Complex x;
inputNmbr(&x);
printNmbr(x);
return 0;
}
推荐阅读
- python - 将 Python 参数传递给模块
- ruby-on-rails - 在 Rails 中根据 url 应用锚标签
- bash - Shell 脚本命令超时
- javascript - React Routing - 如何使用路由加载弹出窗口
- javascript - 将 JSON 数据从 Python 发送到 Javascript 并访问它们。
- jquery - 如何通过使用委托展开和折叠父母和孩子来使用 jquery 创建自定义手风琴
- hardware - 如果我们直接将外围电路用于微处理器会发生什么?
- javascript - 以角度 6 绑定来自服务的图像
- react-native - 一起使用 Tab 和 Stack Navigator
- mysql - 如果事务中没有数据更改,COMMIT 与 ROLLBACK 的成本/性能