【发布时间】:2013-12-18 20:31:23
【问题描述】:
我正在学习 C 语言课程,并且刚刚开始使用函数。我完成了本章实验室的代码,它运行正常。然后我去查看了实验室包含的正确答案代码,它与我的不同。
我的在 main 区域的函数调用中有“printf”,但实验室的正确答案代码在 main 区域之外有 printf,但是当您运行程序时它们都得到完全相同的结果。
这让我很困惑。似乎在 C 中总是有两种不同的方法可以做完全相同的事情。
谁能给我解释一下?
我的代码:
#include <stdio.h>
void closing(void);
int addSix(int x);
int main()
{
closing();
closing();
for(int index=0; index<10; index++) {
printf("Result: %d\n", addSix(index));
}
return 0;
}
void closing(void)
{
printf("That's all folks!\n");
}
int addSix(int x)
{
int result = x+6;
return result;
}
实验室的正确答案代码:
#include <stdio.h>
void closing(void);
void addSix(int x);
int main ()
{
closing();
closing();
for(int i = 0; i<10; i++){
addSix(i);
}
return 0;
}
void closing(void)
{
printf("That's all folks.\n");
}
void addSix(int x)
{
int result = x+6;
printf("Result: %d\n", result);
}
【问题讨论】:
-
在 C 或任何其他编程语言中,有许多不同的方法可以做任何事情。您的代码实际上在功能上等同于“正确”答案。
-
在 C 中不仅有两种方法,而且有很多方法可以做同样的事情。
-
代码的正确与否不能说,如果结果和预期一样,说明代码正确。您的解决方案和解决方案一样好。
-
函数名是
addSix而不是addSixAndPrint。您的代码更正确。