最近开始啃Robert Sedgewick与Kevince Wayne著的《算法》,是由我的一个师弟给我强推的!
里面是Java语言,但自己只会点C++。所以慢慢自己学习写成C++ code.
今天是补上前些天刚看了些的内容,先从简单学起!
Day1–>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Suit up!
1. 求一个数的平方根sqrt.cpp:
用到了牛顿迭代法;
/*************************************************************************
> File Name: sqrt.cpp
> Author: MAQ
> Mail: maq046@163.com
> Created Time: 2019年04月21日 星期一 12时43分46秒
************************************************************************/
#include<iostream>
#include<cmath>
using namespace std;
int main (){
cout << "Please enter a number: "<<endl;
double a;
cin >>a;
double results=a;
double err=0.00000001;
if (a<0){
cerr<< " Please input the non-negative number!!"<<endl;
}
else {
while (abs(results-a/results)>err){
results=(results+a/results)/2;
}
cout << "The square root of "<<a<<" is "<<results<<endl;
}
return 0;
}
g++ sqrt.cpp
./a.out
Please enter a number:
26
The square root of 26 is 5.09902
2. 判断一个数是否为素数? isPrime.cpp
#include<iostream>
using namespace std;
int main(){
cout <<"Please enter a number: "<<endl;
int a;
cin >>a;
if (a<2){
cerr <<"Wrong Number!!"<<endl;
}
else{
bool flag;
for (int i=2;i*i<=a;i++){
if (a%i==0){
flag=false;
break;
}
flag=true;
}
if (flag==false){
cout << a<< " is not a Prime!!"<<endl;
}
else{
cout << a<< " is a Prime!!"<<endl;
}
}
return 0;
}
g++ isPrime.cpp
./a.out
Please enter a number:
25
25 is not a Prime!!
./a.out
Please enter a number:
31
31 is a Prime!!
/今日标签/
活在当下:感受指尖的阳光,品味手中的奶盖乌龙,聆听一首轻快的歌。