c - 在 C 中将代码划分为函数

标签 c function memory

在很长时间没有使用 C 之后,我又回到了 C。我刚刚练习,就遇到了这个问题。我正在尝试:

  1. 从 scanf() 中获取 2 个变量
  2. 将两个输入相乘
  3. 然后输出问题

我试图将不同的部分分成函数,但程序给出的数字非常高(认为它们是内存地址)。这可能是由于我缺乏误解。

#include <stdio.h>

int input();
int mult ( int x, int y );

int main()
{
 int x;
 int y;

 x, y = input();

 printf( "In Main: x, y: %d, %d\n", (x, y) );
 z = mult(x,y);
 printf( "The product of your two numbers is %d\n", z );

 getchar();
 getchar();
}


int input()
{
 int i_x;
 int i_y;    

 printf( "Please input two numbers to be multiplied: " );
 scanf( "%d", &i_x );
 scanf( "%d", &i_y );
 printf( "In Input: x, y: %d, %d\n", i_x, i_y );
 return i_x, i_y;
}


int mult (int x, int y)
{
 int a;
 int b;
 int c;

 a = x;
 b = y;

 printf( "In Multi: x, y: %d, %d\n", a, b );

 c = a*b;

 return c;
}

最佳答案

x, y = input(); 没有执行您期望的操作。您不能从函数返回两个值。您应该阅读 comma operator

我宁愿建议将xy的地址传递给函数input。先改变原型(prototype)

void input(int *, int *);     

然后将其称为

input(&x, &y);

并更改定义

void input(int *i_x, int *i_y)
{
     printf( "Please input two numbers to be multiplied: " );
     scanf( "%d", i_x );
     scanf( "%d", i_y );
     printf( "In Input: x, y: %d, %d\n", *i_x, *i_y );
}

关于c - 在 C 中将代码划分为函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37074058/

相关文章:

c - 在套接字上使用 O_NONBLOCK 后,有没有办法避免 HUP?

c++ - 如何在排序时保持数组的位置相同?

javascript - 如何将单击时的图像源更改为一个源,并在同一单击时返回到不同的源

c++ - 如何为作为函数的函数参数分配默认值? C++

java - Android 效率 - View

调用一个函数,但我无法理解算术逻辑

c - 我想搜索并显示一个 “contact”的信息,但是没有用

c - 使用递归找到二维迷宫路径。段故障。 C

python-3.x - 如何将大型数据库中的数据加载到 pandas 中?

c - 使用 C 用户空间代码从 Linux/proc 接口(interface)读取的最佳方法是什么?