函数
1 分析运行结果
观察以下代码,它的运行结果会是怎么样呢?
cpp
#include <iostream>
using namespace std;
int hello() {
cout << "Hello" << endl;
return 10;
}
int main() {
hello();
hello();
return 0;
}cpp
#include <iostream>
using namespace std;
int hello() {
cout << "Hello" << endl;
return 10;
}
int main() {
cout << hello();
return 0;
}cpp
#include <iostream>
using namespace std;
int hello() {
cout << "Hello" << endl;
return 10;
}
int main() {
int b = hello() + 100;
cout << b;
return 0;
}cpp
#include <iostream>
using namespace std;
int hello(int a) {
return a*100;
}
int main() {
cout << hello(88);
return 0;
}输出示例
2 分析错误
以下代码有语法错误吗? 如有错误,请指出其中的错误。
cpp
#include <iostream>
using namespace std;
void printMessage() {
cout << "Hello from function!" << endl;
}
int main() {
printMessage;
return 0;
}cpp
#include <iostream>
using namespace std;
void 123greet(string name) {
cout << "Hello, " << name << endl;
}
int main() {
123greet("Alice");
return 0;
}cpp
#include <iostream>
using namespace std;
int addNumbers(int a, int b)
return a + b;
}
int main() {
cout << addNumbers(5, 3) << endl;
return 0;
}cpp
#include <iostream>
using namespace std;
int main() {
displayMessage();
return 0;
}
void displayMessage() {
cout << "欢迎学习C++函数!" << endl;
}答案(同学们也可以编译运行,进行验证)
3 分析运行结果
观察以下代码,它的运行结果会是怎么样呢?
cpp
#include <iostream>
using namespace std;
void fun1() {
cout << "函数1" << endl;
}
void fun2() {
cout << "函数2" << endl;
fun1();
}
int main() {
fun2();
cout << "主函数" << endl;
return 0;
}cpp
#include <iostream>
using namespace std;
int add(int a,int b) {
a++;
return a;
return a+b;
}
int main() {
cout << add(7,9);
return 0;
}cpp
#include <iostream>
using namespace std;
int myMinus(int a = 100, int b = 200) {
int result = a - b;
return result;
}
int main() {
int hhh = myMinus() + myMinus(300,100);
cout << hhh;
return 0;
}cpp
#include <iostream>
using namespace std;
int big(int a) {
return a+10;
}
int main() {
cout << big(big(5+5));
return 0;
}输出示例
4 分析错误
以下代码有语法错误吗? 如有错误,请指出其中的错误。
cpp
#include <iostream>
using namespace std;
void a() {
return 0;
}
int main() {
a();
return 0;
}cpp
#include <iostream>
using namespace std;
int a() {
return 3.14;
}
int main() {
cout << a();
return 0;
}