在很长时间没有使用 C 之后,我又回到了 C。我刚刚练习,就遇到了这个问题。我正在尝试:
- 从 scanf() 中获取 2 个变量
- 将两个输入相乘
- 然后输出问题
我试图将不同的部分分成函数,但程序给出的数字非常高(认为它们是内存地址)。这可能是由于我缺乏误解。
#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 。
我宁愿建议将x
和y
的地址传递给函数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/