安徽大学上机题
题目一描述:
输入10个整数(有奇数也有偶数),要求输出其中的每个奇数,并输出奇数个数与奇数之和。
例如:
输入:11,4,3,2,7,6,8,5,10,9
输出:11,3,7,5,9
NUM=5
SUM=35
#include<iostream>
using namespace std;
int main() {
int num[10];
cout << "输入数字:";
for (int i = 0;i < 10;i++)
cin >> num[i];
int count = 0, sum = 0;
for (int i = 0;i < 10;i++) {
if (num[i] % 2 != 0) {
count++;
sum += num[i];
cout << num[i] << " ";
}
}
cout << endl;
cout << "NUM=" << count << endl;
cout << "SUM=" << sum << endl;
return 0;
}
运行测试结果:
题目二描述:
找出1000之内的所有完数,并输出完数和它的所有因子(一个数恰好等于他的因子之和,称为完数,例如:6=1+2+3)。
#include<iostream>
using namespace std;
bool isPerfectNum(int n) {//判断是不是完数
int sum = n;
for (int i = 1;i <= n / 2;i++) {
if (n % i == 0) {
sum = sum - i;
}
}
if (sum == 0) {
return true;
}
else {
return false;
}
}
int main() {
for (int i = 1;i <= 1000;i++) {
if (isPerfectNum(i)) {
cout << i << "是完数:";
for (int j = 1;j <= i / 2;j++) {//输出所有因子
if (i % j == 0)
cout << j << " ";
}
cout << endl;
}
}
return 0;
}
运行测试结果:
题目三描述:
由键盘输入一行仅由英文字母及空格组成的字符,编程实现(相邻单词之间用一个空格或多个空格隔开)
(1)输出每个单词及其长度
(2)输出最长的单词
例如:
输入:I am a boy
输出:
I 1
am 2
a 1
boy 3
the longest word is:boy
#include<iostream>
#include<string>
using namespace std;
//判断是不是字母
bool isCharacter(char c) {
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
return true;
else
return false;
}
int main() {
string str;
cout << "输入字符串:";
getline(cin, str);
int longest = 0, start = 0;//分别用来存储最长单词长度和每个单词的起始位置
int i = 0;//工作指针
char longestWord[50];//用来存储最长单词
while (str[i] != '\0') {
while (str[i] != '\0' && !isCharacter(str[i]))//寻找单词的起始位置
i++;
start = i;
while (isCharacter(str[i]))//寻找单词的末尾
i++;
int length = i - start;//计算出单词的长度
if (length > 0) {//如果长度大于0才是单词
for (int j = start;j < i;j++)//输出单词和长度
cout << str[j];
cout << '\t' << length << endl;
if (length > longest) {//更新最长的单词
int k;
longest = length;
for (k = 0;k < length;k++)
longestWord[k] = str[start + k];
longestWord[k] = '\0';
}
}
}
cout << "The longest word is:" << longestWord << endl;
return 0;
}
运行测试结果: