前言

此系列文章为博主学习C++时的笔记,不保证代码的可用性

3n+1问题

大于1 的自然数n,若n为奇数,则将n变为3n+1,否则变为n的一半,经过若干次变换,最后一定会变为1,n<=10^9

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdio.h>
using namespace std;

int main()
{
int in;
int count=0;
scanf("%d",&in);
while(in!=1)
{
if(in%2!=0)
{
in=3*in+1;
}
else{
in/=2;
}
count++;
}
printf("%d",count);
}

调和级数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<stdio.h>
using namespace std;
int main()
{
int n;
// int count=0;
scanf("%d",&n);
double num=0;
for(int i=1;i<=n;i++)
{
num+=(1.0/i);
// count++;
// printf("%d\n",count);
}
printf("%.3lf",num);
}

反向输出四位数

1
2
3
4
5
6
7
8
9
// https://ac.nowcoder.com/acm/contest/18839/1023?&headNav=acm
#include<stdio.h>
#include<math.h>
using namespace std;
int main(){
int a,b;
scanf("%d",&a);
printf("%d%d%d%d",a%10,a/10%10,a/10/10%10,a/10/10/10%10);
}

阶乘

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>
using namespace std;
int main(){
int input;
long long output=1;
scanf("%d",&input);
for(int i=1;i<=input;i++)
{
output*=i;
}
printf("%lld\n",output);
}

九九乘法表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// https://ac.nowcoder.com/acm/contest/18839/1005
#include <iostream>
using namespace std;
int main(){
for (int i=1;i<10;i++)
{
if(i!=1){
cout<<endl;
}
int _one=1;
for(;_one<=i;_one++){
if(_one==1){
cout<<_one<<"*"<<i<<"="<<" "<<_one*i<<" ";
}
else if(_one==2&&i<5){
cout<<_one<<"*"<<i<<"="<<" "<<_one*i<<" ";
}
else if(_one==3&&i==3)
{
cout<<_one<<"*"<<i<<"="<<" "<<_one*i<<" ";
}
else
{
cout<<_one<<"*"<<i<<"="<<_one*i<<" ";
}
}
}
}

珂朵莉的假动态仙人掌

链接:https://ac.nowcoder.com/acm/contest/18839/1043
来源:牛客网

珂朵莉想每天都给威廉送礼物,于是她准备了n个自己的本子

她想送最多的天数,使得每天至少送一个本子,但是相邻两天送的本子个数不能相同

珂朵莉最多送几天礼物呢?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// https://ac.nowcoder.com/acm/contest/18839/1043
#include <iostream>
using namespace std;
int main(){
int book ;
cin>>book;
if(book%3==0)
{
cout<<(book/3)*2;
}
else if(book%3!=0)
{
if(book%3==1)
{
cout<<(book/3)*2+1;
}
else if(book%3==2)
{
int a= (book/3);
cout<<(book/3)*2+1;
}
}
}

位数判断

1
2
3
4
5
6
7
8
9
10
11
12
13
#include<stdio.h>
using namespace std;
int main(){
int input;
int count=0;
scanf("%d",&input);
while (input!=0)
{
input/=10;
count++;
}
printf("%d",count);
}

已知三角形三边长求周长面积

采用海伦公式

1
2
3
4
5
6
7
8
9
10
11
//https://ac.nowcoder.com/acm/contest/18839/1029
#include<stdio.h>
#include<math.h>
int main(){
double a,b,c;
scanf("%lf %lf %lf",&a,&b,&c);
double p =(a+b+c)/2;
double result =sqrt(p*(p-a)*(p-b)*(p-c));
printf("circumference=%.2lf ",a+b+c);
printf("area=%.2lf",result);
}

π的值

1
2
3
4
5
6
#include<stdio.h>
#include<math.h>
using namespace std;
int main(){
printf("%.3lf",acos(-1));
}