1、编写程序,计算下列分段函数 y=f(x)的值。
y= -x+2.5,0<= x <2
y=2-1.5(x-3)(x-3),2<= x <4
y=x/2-1.5,4<= x <6
#include<stdio.h>
#include<stdlib.h>
#include<cstring>
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
double x,y;
cin>>x;
if(x>=0&&x<2)
y=-x+2.5;
else if(x<4)
y=2-1.5*(x-3)*(x-3);
else if(x<6)
y=x/2-1.5;
else
{
cout<<"x输入范围不正确!"<<endl;
return 0;
}
cout<<y<<endl;
return 0;
}
2. 编写程序,读入一个整数 N。若 N 为非负数,则计算 N 到 2N 之间的整数和;若 N 为一个负数,则求 2N 到 N 之间的整数和
#include<stdio.h>
#include<stdlib.h>
#include<cstring>
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
int N;
int ans=0;
cin>>N;
if(N>=0)
ans=3*N*(N+1)/2;
else
ans=3*N*(-N+1)/2;
cout<<ans<<endl;
return 0;
}
3. 设 N 是一个四位数,它的 9 倍恰好是其反序数(例如:1234 的反序数是 4321),求 N 的值。
#include<stdio.h>
#include<stdlib.h>
#include<cstring>
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
int N;
int a,b,c,d;
for(N=1000;N<=9999&&N*9<=9999;N++)
{
a=N/1000;
b=(N-1000*a)/100;
c=(N-1000*a-100*b)/10;
d=N%10;
if(N*9==(d*1000+c*100+b*10+a))
cout<<N<<endl;
}
}
4.N 个人围成一圈顺序编号,从 1 号开始按 1、2、 3 顺序报数,报 3 者退出圈外,其余的人再从 1、2、 3 开始报数,报 3 的人再退出圈外,依次类推。请按退出顺序输出每个退出人的原序号。要求使用环形链表编程。
#include<cstring>
#include<iostream>
using namespace std;
struct circle
{
int num;
circle *next;
};
int main()
{
circle *h,*t,*head;
int n;
cin>>n;
h=new circle;
h->num=1;
h->next=NULL;
head=h;
for(int i=2;i<=n;i++)
{
t=new circle;
t->num=i;
t->next=NULL;
h->next=t;
h=t;
}
t->next=head;
int i=3;
head=head->next;
h=head->next;
while(n!=0)
{
if(i%3==0)
{
cout<<h->num<<" ";
head->next=h->next;
h=h->next;
n--;
}
else
{
h=h->next;
head=head->next;
}
i++;
}
}
5. 请输入高度 h,输入一个高为 h,上底边长为 h的等腰梯形(例如 h=4,图形如下)。
****
******
********
**********
#include<cstring>
#include<iostream>
using namespace std;
int main()
{
int h;
cin>>h;
for(int i=1;i<=h;i++)
{
for(int j=h-i+1;j>0;j--)
cout<<" ";
for(int j=0;j<h;j++)
cout<<"*";
for(int j=1;j<i;j++)
cout<<"**";
cout<<endl;
}
return 0;
}
6. 请编写一个程序,从键盘上输入 n(n 的范围是1~20),求 n 的阶乘。(注意结果要用long long类型)
#include<cstring>
#include<iostream>
using namespace std;
int main()
{
int n;
long long ans=1;
cin>>n;
for(int i=1;i<=n;i++)
ans*=i;
cout<<ans<<endl;
return 0;
}
7. 从键盘上任意输入一个长度不超过 20 的字符串,对所输入的字符串,按照 ASCII 码的大小从小到大进行排序,请输出排序后的结果
#include<cstring>
#include<iostream>
using namespace std;
int main()
{
string str;
char temp;
cin>>str;
int len=str.length();
for(int i=0;i<len;i++)
for(int j=i;j<len;j++)
if(str[i]>str[j])
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
}
for(int i=0;i<len;i++)
cout<<str[i];
cout<<endl;
return 0;
}