首页 > 解决方案 > 按值传递变量,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

标签: c

解决方案


我没有完成你所有的执行,但是,你不正确的问题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;
   }

推荐阅读