C++ 上机课参考答案
本系列文章供北京邮电大学信通院及数媒学院「C++高级程序语言设计」上机课学生参考。
2016-2017学年第二学期C++第三章(1)
1495.VC++实验3.1 闰年
//VC++实验3.1 闰年
//闰年规则:非整百年能被4整除为闰年,2004是,2100不是;整百年能被400整除为闰年,2000是,1900不是。
#include <iostream>
using namespace std;
int main()
{
int year;
cin >> year;
(((year % 4 == 0) && (year % 100 != 0))||(year % 400 == 0))? // && 是与运算符 || 是或运算符
cout << "是" << endl : cout << "不是" << endl;
/*另外一种写法
int year;
cin >> year;
if(((year % 4 == 0) && (year % 100 != 0))||(year % 400 == 0))
{
cout << "是" << endl;
}
else
{
cout << "不是" << endl;
}
*/
return 0;
}
1496.VC++实验3.2 欧几里德算法
//VC++实验3.2 欧几里德算法
#include <iostream>
using namespace std;
int main()
{
int a, b, c;
cin >> a >> b;
while(a % b != 0)
{
c = a % b;
a = b;
b = c;
}
cout << b << endl;
return 0;
}
1497.VC++实验3.3 输出ASCII字符
//VC++实验3.3 输出ASCII字符
#include <iostream>
using namespace std;
int main()
{
int n, i;
cin >> n;
for(i = 0; i < 10; i++)
{
cout << (char)(n + i) << " ";
}
return 0;
}
1498.VC++实验3.4 显示三角形
//VC++实验3.4 显示三角形
#include <iostream>
using namespace std;
int main()
{
int n, i, j;
cin >> n;
for(i = 1; i <= n; i++)
{
for(j = n; j > i; j--)
{
cout << ' ';
}
for(j = 1; j <= 2 * i - 1; j++)
{
cout << '*';
}
cout << endl;
}
return 0;
}
1500.VC++实验3.6 求和逼近
//VC++实验3.6 求和逼近
#include <iostream>
using namespace std;
int main()
{
int x, sum = 0, n, j = 1;
cin >> x;
for(n = 1; sum <= x; n++)
{
j *= n;
sum += j;
}
cout << n - 2;
return 0;
}