完成构建之法第二章后面的小实践~

练习数值计算。找出一个整数数组中子数组之和的最大值,例如:数组【1,-2,3,5,-1】,返回8,因为符合要求的子数组是【3,5】;

程序代码如下,使用的是C语言:

#include<stdio.h>
int Serch(int a[],int n)
{
int i,temp;
for(i=1;i<n;i++)
{
if(a[0]<a[i])
{
temp=a[0];
a[0]=a[i];
a[i]=temp;
}
}
for(i=2;i<n;i++)
{
if(a[1]<a[i])
{
temp=a[1];
a[1]=a[i];
a[i]=temp;
}
}
return (a[1]+a[0]);
}
void main()
{
int a[100],n,i;
printf("请输入数组长度:");
scanf("%d",&n);
printf("请输入数组值:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("%d\n",Serch(a,n));
}

字符串操作。把一个英语句子中单词的次序颠倒后输出。例如输入:how are you,则输出 you are how

这个可以用指针实现,先把每个单词逆序,再将整个句子逆序,下面提供一种C++输入流的

#include <iostream>
#include <string>
#include <sstream>
#include <stack>
using namespace std;
string str;
stack<string> st;
int main()
{
while(getline(cin,str))
{
istringstream mystring(str);
bool isfirst = true;
while ( mystring >> str )
{
st.push(str);
}
while ( !st.empty() )
{
if ( isfirst )
{
isfirst = false;
cout<<st.top();
}
else
{
cout<<" "<<st.top();
}
st.pop();
}
cout<< endl;
}

return 0;
}

 

posted @ 2017-04-23 15:23  ☆李凯城☆  阅读(134)  评论(0编辑  收藏  举报