定义一个函数CoordTransform(),用于转换其前两个输入 参数xVal和yVal分为两个输出参数xValNew和 yValNew。该函数返回void。转型是新的=(旧+ 1)* 2.例如:如果xVal = 3且yVal = 4,则xValNew为8,yValNew为 10。
问题:我必须制作此代码,它是用于教科书中的作业。我对整个部分并不十分了解。所以,我要求帮助和解释。谢谢!
我的代码如下:
#include <stdio.h>
/* Your solution goes here */
void CoordTransform( int* xValNew, int* yValNew)
{
*xValNew = ((xValNew +1) * 2);
*yValNew = ((yValNew +1) * 2);
return;
}
int main(void) {
int xValNew = 0;
int yValNew = 0;
CoordTransform(3, 4, &xValNew, &yValNew);
printf("(3, 4) becomes (%d, %d)\n", xValNew, yValNew);
return 0;
}
答案 0 :(得分:1)
您的规格说“ ...将其前两个输入参数xVal和yVal转换为两个输出参数xValNew和yValNew ”,因此您的函数应该具有四个参数,而不是二:
/* Your solution goes here */
void CoordTransform( int xVal, int yVal, int* xValNew, int* yValNew)
{
*xValNew = ((xVal +1) * 2);
*yValNew = ((yVal +1) * 2);
}
int main(void) {
int xValNew;
int yValNew;
CoordTransform(3, 4, &xValNew, &yValNew);
printf("(3, 4) becomes (%d, %d)\n", xValNew, yValNew);
return 0;
}
答案 1 :(得分:1)
CoordTransform()的代码应该是:
#include <stdio.h>
void CoordTransform(int xVal, int yVal, int *xValNew, int *yValNew) {
*xValNew = ((xVal +1) * 2);
*yValNew = ((yVal +1) * 2);
}
int main(void) {
int xValNew;
int yValNew;
CoordTransform(3, 4, &xValNew, &yValNew);
printf("(3,4) becomes (%d, %d)\n", xValNew, yValNew);
return 0;
}
这个练习的主要目的是区分传递参数的值,如xVal和yVal,以便在不改变它们的情况下使用这些值,并通过地址或引用传递参数,如xValNew和yValNew,如果你打算改变它的值这些输出参数。
答案 2 :(得分:0)
你给一个只接受2的函数提供了4个参数,在你的函数CoordTransform中,你应该取消引用指针来获取值
/* Your solution goes here */
void CoordTransform( int* xValNew, int* yValNew)
{
*xValNew = ((*xValNew +1) * 2);
*yValNew = ((*yValNew +1) * 2);
return;
}
(由于函数的类型无效,因此不需要return语句)