指出下面程序中的错误,说明错误的原因,并进行改正 #include <iostream>using namespace std;class Student {public: char name[10]; int age; float aver; void printStu();};int main() { Student p1,p2,p3; p1.age = 30; return 0;}
时间: 2024-01-15 12:03:33 浏览: 31
该程序存在两个错误,包括:
1. `#include <iostream>using namespace std;` 应改为 `#include <iostream> using namespace std;`
2. `Student p1,p2,p3;` 中的逗号应该为英文逗号,否则编译器将无法正确识别变量声明。应改为 `Student p1, p2, p3;`
改正后的代码如下:
```
#include <iostream>
using namespace std;
class Student {
public:
char name[10];
int age;
float aver;
void printStu();
};
int main() {
Student p1, p2, p3;
p1.age = 30;
return 0;
}
```
相关问题
指出下面程序中的错误,说明错误的原因,并进行改正 #include <iostream> using namespace std; class Student { public: char name[10]; int age; float aver; void printStu();};int main() { Student p1,p2,p3; p1.age = 30; return 0;}
该程序没有显式的错误,但是可以进行一些改进:
1. 建议在 `printStu()` 函数中添加输出语句,否则该函数将不能正确输出学生信息。
2. 建议在 `printStu()` 函数中添加换行符,使输出更加美观。
改进后的代码如下:
```
#include <iostream>
using namespace std;
class Student {
public:
char name[10];
int age;
float aver;
void printStu();
};
void Student::printStu() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Average: " << aver << endl << endl;
}
int main() {
Student p1, p2, p3;
p1.age = 30;
p1.printStu();
return 0;
}
```
指出下列程序的错误,说明错误的原因并改正。 #include <iostream> using namespace std; class Student { string name; float score; static int total; int Student (const char n, float s) { name = n; total += s; return 0; } }; int main() { int Student::total = 0; Student s1("张三", 95); Student s2("李四", 90); Student s3("王五", 85); cout << "总分=" << total << endl; }
这个程序有以下错误:
1. 在 class Student 中的构造函数应该是 public,而不是 private。
2. 构造函数的参数类型应该是 const char* 而不是 const char。
3. 在构造函数中,total += s 应该改为 score = s; total += s;。
4. 在 main 函数中,应该先声明并初始化静态变量 total,然后才能创建对象。
5. 在 main 函数中,输出总分时应该使用类名 Student::total 而不是 total。
下面是改正后的程序:
```
#include <iostream>
#include <string>
using namespace std;
class Student {
string name;
float score;
static int total;
public:
Student(const char* n, float s) {
name = n;
score = s;
total += s;
}
};
int Student::total = 0;
int main() {
Student s1("张三", 95);
Student s2("李四", 90);
Student s3("王五", 85);
cout << "总分=" << Student::total << endl;
return 0;
}
```
改正后的程序中,构造函数被声明为 public,参数类型改为 const char*,在构造函数中同时给 name 和 score 赋值,先声明并初始化静态变量 total,然后才能创建对象,输出总分时使用类名 Student::total。