C++习题一 – 作者:Johnson666

一、改错题:修改以下程序,并给出正确代码及运行结果

(1)从键盘输入a和b的值,并输出两数的和。 image.png代码:

#include <iostream>
using namespace std;
int main()
{
int a, b;
cout << "please input the numers a b:";
cin >> a >> b;
cout << "a+b:" << a+b <<endl;
return 0;
}

运行结果:

image.png

(2)从键盘输入a的值,输出c的结果。

image.png

代码:

#include <iostream>
int main()
{
int a,c;
char b='D';
a = 1;
c = a + b;
std::cout << "c:" << c << std::endl;
return 0;
}

运行结果:

image.png

(3)从键盘输入a和c的值,求余并输出结果。

image.png

代码:

#include <iostream>
int main()
{
int a = 0, b = 0;
int c = 0;
std::cin >> a >> c;
b = a % c;
std::cout << "b:" << b << std::endl;
return 0;
}

运行结果:

image.png

二、请在VC++6.0中调试并运行以下的程序,给出运行结果

(1)程序1:掌握循环语句嵌套的使用方法

image.png

运行结果:

image.png

(2)程序2:掌握break语句的使用方法

image.png

运行结果:

image.png

(3)程序3:掌握continue语句的使用方法

image.png

运行结果:

image.png

三、请在VC++6.0中编写以下C++程序,并给出代码及运行结果

(1)从键盘输入一个年份,判断是否是闰年。

提示:闰年判断条件:能被4整除而不能被100整除;能被400整除。

代码:

#include <iostream>
using namespace std;
int main()
{
while(1)
{
int year;
cout << "please input a year:";
cin >> year;
if(year % 4 == 0 && year % 100 != 0)
{
cout << "it is run year!" << endl;
}
else if(year % 400 == 0)
{
cout << "it is run year!" << endl;
}
else
{
cout << "it is pin year!" << endl;
}
}
return 0;
}

运行结果:

image.png

(2)从键盘输入一个年份和月份,判断该月有多少天。提示:

1,3,5,7,8,10,12 31天

4,6,9,11 30天

2 闰年 29天

平年 28天

代码:

#include <iostream>
using namespace std;
int main()
{
while(1)
{
int year, month;
cout << "please input a year and the month:";
cin >> year >> month;
if(year % 4 == 0 && year % 100 != 0)
{
year = 0;
}
else if(year % 400 == 0)
{
year = 0;
}
else
{
year = 1;
}
if(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
{
cout << "it has 31 days!" << endl;
}
else if(month == 4 || month == 6 || month == 9 || month == 11)
{
cout << "it has 30 days!" << endl;
}
else
{
if(year ==0)
cout << "it has 29 days!" << endl;
else
cout << "it has 28 days!" << endl;
}
}
return 0;
}

运行结果:

image.png

(3)使用循环的嵌套解不定方程组: 有100个学生种100棵树,其中高中生每人种3棵树,初中生每人种2棵树,小学生每3人种1棵树,问高中生、初中生、小学生各有多少人?

代码:

#include <iostream>
using namespace std;
int main()
{
int x, y, z;
for(x = 0; x <= 100; x++)
{
for(y = 0; y <= 100; y++)
{
for(z = 0; z <= 100; z++)
{
if((x + y + z == 100) && (3 * x + 2 * y + z / 3.0 == 100.0))
{
cout << x << ' ' << y << ' ' << z << ' ' << endl;
}
}
}
}
return 0;
}

运行结果:

image.png

(4)按如下形式打印九九乘法口诀表:

1*1=1

2*1=2 2*2=4

3*1=3 3*2=6 3*3=9

……

9*1=9 9*2=18 9*3=27 … 9*9=81

代码:

#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <=9; i++)
{
for (int j = 1; j <= i; j++)
{
cout << j << "*" << i << "=" << i * j << "\t";
}
cout << endl;
}
return 0;
}

运行结果:

image.png

来源:freebuf.com 2021-03-18 09:42:05 by: Johnson666

© 版权声明
THE END
喜欢就支持一下吧
点赞0
分享
评论 抢沙发

请登录后发表评论