关闭

循环-01~~~05

标签: PAT
123人阅读 评论(0) 收藏 举报

循环-01

#include<iostream>
#include<iomanip>
int main()
{
using namespace std;
cout << fixed << right;
int a, b; int tot = 0;
cout << "ENter two integer between -100~100:\n";
if (cin >> a >> b)
{
for (int i = a; i < b + 1; i++)
{
tot += i;
cout << setw(5)<<i;
if ((i - a) % 5 == 4)
cout << endl;
}
}
cout << "\nTotal number =" << tot << endl;
return 0;
}


循环-02

#include<iostream>
#include<cmath>
int main()
{
using namespace std;
int n = 0; double m = 1.0;
float sum = 1.0;
double lim;
cout << "Enter your expected limitation :\n";
cin >> lim;
while (m > lim)
{
n++;
m = m*n / (2 * n + 1);
sum += m;
}
cout.setf(ios_base::fixed,ios_base::floatfield);
cout.precision(6);
cout << "We get pi=" << 2 * sum << endl;
return 0;
}


循环-03

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void show(const vector<int>&v,int );
int main()
{
int n; int result; int num = 0;
vector<int>line;
cout << "Enter a number no more than 6:";
cin >> n;
for (int i = n; i < n + 4; i++)
{
for (int j = n; j < n + 4;j++)
{
if (j != i)
{
for (int k = n; k < n + 4; k++)
{
if (k != i&&k != j)
{
result = 100 * i + 10 * j + 1 * k;
line.push_back(result);
num++;
}
}
}
}
}
cout << "We have total " << num << " scequence .\n";
sort(line.begin(), line.end());
show(line, 6);
return 0;
}
void show(const vector<int>&v, int n)
{
for (int i = 0; i < v.size(); i++)
{
if (i % n == (n-1))
cout << v[i] << endl;
else
cout << v[i]<<' ';
}
}


循环-04

#include<iostream>
#include<cmath>
#include<cstdlib>
bool just(int n);
int main()
{
using std::cin; using std::cout; using std::endl;
cout << "Enter a double number:";
int num; cin >> num;
if (num % 2 != 0)
exit(EXIT_FAILURE);
for (int i = 3; i < num / 2; i = i + 2)
{
if (just(i) && just(num - i))
{
cout << "We have " << i << ',' << num - i <<" as expected."<< endl;
break;
}
}
return 0;
}
bool just(int n)
{
int count = 0;
for (int i = 2; i < n / 2; i++)
{
if (n%i == 0)
count++;
}
if (count == 0)
return true;
else
return false;
}


循环-05

#include<iostream>
#include<cmath>
int power(int a, int b);
int main()
{
using namespace std;
long sum = 1;
int month=1; int lim;
cout << "Enter your expected numbeere:";
cin >> lim;
while (2 * sum < lim)
{
if (month>2&&month % 2 == 1)
{
int i = month / 2;
sum=power(2, i);
}
month++;
}
cout << "For the " << month-1 << "st month, rabits is enough.\n";
return 0;
}
int power(int a, int b)
{
int result = 1;
for (int i = 0; i < b; i++)
result *= a;
return result;
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:55331次
    • 积分:2955
    • 等级:
    • 排名:第12372名
    • 原创:250篇
    • 转载:0篇
    • 译文:1篇
    • 评论:25条
    最新评论