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 <cstdio>
float f(float x)
{
float y;
if(x>=0 && x<2)
y=-x+2.5;
else if(x>=2 && x<4)
y=2-1.5*(x-3)*(x-3);
else if(x>=4 && x<6)
y=x/2-1.5;
return y;
}
int main()
{
float x,y;
printf("请输入x\n");
scanf("%f",&x);
if(x<0 || x>=6)
{
printf("x输入有误,请重新输入\n");
return 0;
}
printf("%g",f(x));
return 0;
}
2、编写程序,读入一个整数 N。若 N 为非负数,则计算 N 到 2N 之间的整数和;若 N 为一个负数,则求 2N 到 N 之间的整数和。
#include <cstdio>
int main()
{
int i,n,sum=0;
printf("请输入n的值\n");
scanf("%d",&n);
if(n>0)
for(i=n;i<=2*n;i++)
{
sum+=i;
}
if(n<0)
for(i=2*n;i<=n;i++)
{
sum+=i;
}
printf("%d",sum);
}
3、设 N 是一个四位数,它的 9 倍恰好是其反序数(例如:1234 的反序数是 4321),求 N 的值。
#include <iostream>
#include <string>
using namespace std;
int getfanxu(int num)
{
int result=0;
while(num!=0)
{
result=result*10+(num)%10;
num=num/10;
}
return result;
}
int main()
{
int ni;
int i;
for(i=1000;i<=1111;i++)
{
if(i*9==getfanxu(i))
cout<<i<<" ";
}
}
结果为1089
4、N 个人围成一圈顺序编号,从 1 号开始按 1、2、 3 顺序报数,报 3 者退出圈外,其余的人再从 1、2、 3 开始报数,报 3 的人再退出圈外,依次类推。请按退出顺序输出每个退出人的原序号。要求使用环形链表编程。
#include <cstdio>
#include <iostream>
using namespace std;
typedef struct node
{
int num;
struct node* next;
}Node,*LNode;
void Create(LNode &L,int n)
{
LNode p,r;
for(int i=0;i<n;i++)
{
if(L==NULL)
{
L=(LNode)malloc(sizeof(Node));
L->next=L;
L->num=i+1;
r=L;
}
else
{
p=(LNode)malloc(sizeof(Node));
p->num=i+1;
p->next=r->next;
r->next=p;
r=p;
}
}
}
void Create1(LNode L,int n) //本想试一试把所有的空间一起申请了,可是发现不行,因为next没有串起来,智能一个一个来
{
LNode p,r;
int i=1;
L=(LNode)malloc(n*sizeof(Node));
for(p=L;p;p=p->next)
{
p->num=i++;
if(p->next=NULL)
{
p->next=L;
break;
}
}
}
int main()
{
int n,i=1;
scanf("%d",&n);
LNode L=NULL,r,p;
Create(L,n);
r=p=L;
while(p->next!=p) //若仅剩一个节点,结束循环
{
if(i++%3==0)
{
r->next=p->next;
printf("%d -> ",p->num);
free(p);
p=r->next;
}
else
{
r=p;p=p->next;
}
}
printf("%d\n",p->num);
return 0;
}
版权声明:本文为qq_36834256原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。