我试图编写一个程序依赖函数调用来计算3x ^ 5 + 2x ^ 4-5x ^ 3-x ^ 2 + 7x-6。但是,它会为我的函数返回0的值。
#include <stdio.h>
int function(int x, int polynomial)
{
polynomial = (3 * x * x * x * x * x) + (2 * x * x * x * x) - (5 * x * x * x) - (2 * x * x) + (7 * x) - 6;
return polynomial;
}
int main(void)
{
int x, polynomial;
printf("The program will compute the following polynomial: \n");
printf("3x^5 + 2x^4 - 5x^3 - x^2 + 7x - 6 \n");
printf("Please enter a value for x: ");
scanf("%d", &x);
function(x, polynomial);
return 0;
}
为什么这样做?如何将函数中的值返回到main?
答案 0 :(得分:3)
将变量的值分配给名为function
的函数返回的内容:
#include <stdio.h>
int function(int x)
{
polynomial = (3 * x * x * x * x * x) + (2 * x * x * x * x) - (5 * x * x * x) - (2 * x * x) + (7 * x) - 6;
return polynomial;
}
int main(void)
{
int x, result;
printf("The program will compute the following polynomial: \n");
printf("3x^5 + 2x^4 - 5x^3 - x^2 + 7x - 6 \n");
printf("Please enter a value for x: ");
scanf("%d", &x);
result = function(x);
/* do something with result, like print it */
return 0;
}
(理想情况下,您不会调用函数function
,而是调用其他内容。)
如果您真的想要修改解除引用的指针,那么您需要进行一些更改:
#include <stdio.h>
void function(int x, int* polynomial)
{
*polynomial = (3 * x * x * x * x * x) + (2 * x * x * x * x) - (5 * x * x * x) - (2 * x * x) + (7 * x) - 6;
}
int main(void)
{
int x, result;
printf("The program will compute the following polynomial: \n");
printf("3x^5 + 2x^4 - 5x^3 - x^2 + 7x - 6 \n");
printf("Please enter a value for x: ");
scanf("%d", &x);
function(x, &result);
/* do something with result, like print it */
return 0;
}
在这种情况下,function
是void
,因此不返回任何内容。您传递值x
和result
的内存地址。该内存地址在function
中被取消引用,然后取消引用的地址可以将其值设置为最终的polynomial
。
离开function
并返回main
后,result
的值包含function
中执行的计算。