第一题
思路解析
对于一个数字,我们直接按照题目给的提示去计算即可,当然我们也可以使用后面会学到的循环去获取对应的值存放在数组中,最后输出的时候再获取即可,只需要将原本的数量除以10,即可得到结果,另外建议同学们命名变量的时候规范命名,对比较重要的一些变量取一些有意义的字符串,嫌长可以缩写,哪怕是拼音也要比随便取的n,d,h之类要好,如果只是暂时用到的变量,可以只是简单命名。
int num, h, d, s;
cin>>num;
h=num/100;
d=(num/10)%10;
s=num%10;
cout<<num<<"的百位数字是"<<h<<",十位数字是"<<d<<",个位数字是"<<s;
return 0;
第二题
思路解析
这题需要掌握ascii码的知识,在计算机中,常见的字符都会被登记在ascii表,从而使得字符可以转化为数字被计算机识别(汉字的转化规则更为复杂,有兴趣的同学可以搜索机内码,国标码,区位码自行了解)。在表中字符‘0’对应的是48,字符‘A’对应的是65,字符‘a’对应的是97,依此即可实现转化
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
// 请在此添加代码
/********** Begin *********/
int num, n;
char ch;
cin >> num;
n = num / 1000;
num %= 1000;
ch = n + 12 + 'A';
cout << ch;
n = num / 100;
num %= 100;
ch = n + 12 + 'A';
cout << ch;
n = num / 10;
num %= 10;
ch = n + 12 + 'A';
cout << ch;
ch = num + 12 + 'A';
cout << ch << endl;
/********** End **********/
return 0;
}
第三题
思路解析
这题的关键就是利用好sqrt()函数实现浮点数运算,主要是让大家认识一下数学库,感兴趣的同学可以调用max(),min()等其他方法学习下,也可以省去一部分敲代码的功夫
#include <iostream>
#include <cstdio>
#include <cmath>
#include <iomanip>
using namespace std;
int main()
{
int x1, y1, x2, y2;
double distance;
cin >> x1;
cin.get();
cin >> y1;
cin >> x2;
cin.get();
cin >> y2;
distance = sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
cout << '(' << x1 << ',' << y1 << ")和(" << x2 << ',' << y2 << ")之间的距离是:";
cout << setiosflags(ios::fixed) << setprecision(2) <<distance <<endl;
return 0;
}
第四题
思路解析
第一问中,我们已经知道如何获取各个位数上的数字,在这里,我们需要学习的是循环的概念。循环就是为执行大量重新操作而使用的一种代码方法,比如从1加到100,如果直接敲代码相加那将过于庞大,此处就需要循环。常见的循环有两种,for循环和while循环,语法格式如下:
for(初始条件 : 结束条件: 每一次循环之后执行的操作)
{每一次循环过程需要执行的操作}
while(循环退出的条件)
{每一次循环过程需要执行的操作}
那么如何判断数字是否只有一位数呢?直接与9比大小即可,代码如下:
#include<iostream>
#include <stdio.h>
using namespace std;
int main()
{
int num;
cin>>num;
int m;
while (num>9)
{
m=0;
while (num>0)
{
m+=(num%10);
/=10;
}
n=m;
}
cout<<n<<endl;
return 0;
}
第五题
思路解析
依据质数的定义,我们可以直接给出一个判断某个数num是否是质数的方法,也就是从2~num-1,每个数依次判断是否可以被num整除,如果找不到,就说明这个数是质数,那么可不可以进一步简化呢,实际上,当超过sqrt(num)之后,剩下的数就没必要判断了,道理很简单,如果一个数x大于sqrt(num)并且x可以被num整除,那么num/x一定小于sqrt(num),j可以得出num/x一定早就被验证过了,以此,我们可以写出下列代码
#include <iostream>
#include <iomanip>
#include <cstdio>
using namespace std;
int main()
{
int input = 0;
std::cin >> input;
int max=0;
int count=0;
bool isPrims=false;
for(int i=2;i<input;i++)
{
isPrims=true;
for(int j=2;j*j<=i;j++)
{
if(i%j==0)
{
isPrims=false;
break;
}
}
if(isPrims)
{
count++;
}
}
std::cout << "共有" << count << "个质数严格小于数字" << input << std::endl;
return 0;
}