大一上 c + +上机实验总结目录:返回目录
1、上机调试下列程序,并理解运行结果。
①
#include<iostream>
using namespace std;
int main()
{int x,y,z;
x=3;
y=++x+3;
cout<<x<<","<<y<<endl;
z=(x++)+5;
cout<<x<<","<<z<<endl;
return 0;
}
运行结果:
4,7
5,9
Press any key to continue
②
#include<iostream>
using namespace std;
int main()
{
int i1=2,i2=2,j1,j2;
j1=i1++;j2=++i2;
cout<<j1<<","<<j2<<endl;
cout<<i1++<<","<<++i2; return 0;
}
运行结果:
2,3
3,4Press any key to continue
2、教材P33-P34三、程序练习
①
#include <iostream>
using namespace std;
int main()
{
int a = 1, b = 2;
bool x, y;
cout << (a++)+(++b) << endl;
cout << a % b << endl;
x = !a>b;
y = a-- && b;
cout << x << endl;
cout << y << endl;
}
【解答】
4
2
0
1
②
#include <iostream>
using namespace std;
int main()
{
int x,y,z,f;
x = y = z = 1;
f = --x || y-- && z++;
cout << "x = " << x << endl;
cout << "y = " << y << endl;
cout << "z = " << z << endl;
cout << "f = " << f << endl;
}
【解答】
x=0
y=0
z=2
f=1
3、P35 二、程序设计的第3题
编写一个程序。要求输入一个5位正整数,然后分解出它的每位数字,并将这些数字按间隔2个空格的逆序形式打印输出。例如,用户输入42339,则程序输出如下结果:
9 3 3 2 4
【解答】
#include<iostream>
using namespace std;
int main()
{
int t;
cout<<"Input one integer for 5 bit: ";
cin>>t;
cout<<t%10<<" "<<t/10%10<<" "<<t/100%10<<" "<<t/1000%10<<" "<<t/10000<<endl;
return 0;
}
4、要求按照考试成绩的等级输出百分制分数段,A等为85分以上,B等为70~84分,C等为60~69分 ,D等为 60分以下 。成绩的等级由键盘输入。(用switch实现)
【解答】
#include<iostream>
using namespace std;
int main()
{
char grade;
cout<<"请输入等级:\n";
cin>>grade;
switch(grade)
{
case 'A':cout<<"85分以上"<<endl;break;
case 'B':cout<<"70~84分"<<endl;break;
case 'C':cout<<"60~69分"<<endl;break;
case 'D':cout<<"60分以下"<<endl;break;
default:cout<<"输入有误!"<<endl;
}
return 0;
}
5、用switch语句编写程序,根据成绩打印出等级。
学生成绩是100分制,用score变量记录成绩。(用switch实现)
90-100 输出等级‘A’,
80-89 输出等级‘B’
70-79 输出等级‘C’
60-69 输出等级‘D’
score<60,输出等级‘E’
【解答】
用switch实现:
#include <iostream>
using namespace std;
int main()
{float score;
char grade;
cout<<"请输入学生成绩:";
cin>>score;
while(score>100||score<0)
{cout<<"\n输入有误,请重输";
cin>>score;
}/*错误处理,不是必须的*/
switch((int)(score/10)) /*或(int)score/10*/
{ case 10:
case 9:grade=‘A’;break;
case 8:grade=‘B’;break;
case 7:grade=‘C’;break;
case 6:grade=‘D’;break;
case 5:
case 4:
case 3:
case 2:
case 1:
case 0:grade=‘E’;
}
cout<<"成绩是:"<<score<<endl<<"相应的等级是:"<<grade<<endl;
return 0;
}
6、计算自然数1到n的平方和。
参考程序:
#include <iostream>
using namespace std;
int main()
{
int n,i,sum=0;
cout<<"input n:\n";
cin>>n;
i=1;
while(i<=n)
{sum=sum+i*i;
i++;}
cout<<"1~n的平方和为:"<<sum<<endl;
return 0;
}
本文是大一上学期C++上机实验的总结,涵盖了程序调试、教材练习及程序设计问题。内容包括理解并调试程序、根据教材完成练习、设计分解5位正整数并逆序输出的程序,以及根据百分制成绩输出对应等级的switch实现。通过这些实验,加深了对C++编程的理解和应用。
&spm=1001.2101.3001.5002&articleId=96463219&d=1&t=3&u=ccfb92d4897541ad98a5c6b4981b9616)
6916

被折叠的 条评论
为什么被折叠?



