分段函数
#include <cstdio>
#include <cmath>
#include <vector>
double function(double x){
double y=0;
if(0<=x&&x<2) y=2.5-x;
else if(2<=x&&x<4) y=2-1.5*pow(x-3,2);
else if(4<=x&&x<6) y=x/2-1.5;
return y;
}
int main(){
std::vector<double> vec;
int m;
scanf("%d",&m);
double x;
for(int i=0;i<m;i++){
scanf("%lf",&x);
vec.push_back(function(x));
}
for(int j=0; j<m; j++){
if(j==m-1) printf("y=%.1f",vec[j]);
else printf("y=%.1f\n",vec[j]);
}
return 0;
}
Error:
错:vector<double> vec;
对:std::vector<double> vec;
原因:《算法笔记》胡凡
阶乘
#include <cstdio>
#include <vector>
int main(){
std::vector<long long> vec;
int m,n;
scanf("%d",&m);
long long sum;
for(int j=0;j<m;j++){
scanf("%d",&n);
sum=1;
for(int i=1;i<=n;i++) sum*=i;
vec.push_back(sum);
}
for(int k=0;k<m;k++) printf("%lld\n",vec[k]);
return 0;
}
提示:注意输出结果可能超32位整型。所以定义long long 型
围圈报数
从零开始的c语言链表学习 001--创建一个最简单基础的链表
题目要求使用环形链表。其实很简单,就是处理好节点的删除就好了。以下是C++代码实现。核心程序不多,在init是构造环形链表。主要语句是main里面的一句while,这里的head就是当前要准备退出的,接下来删除它即可。
//重点:while((head = head->next)&&--k);
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
typedef struct Node{
int index;
struct Node *next;
struct Node *pre;
}Node,*Nodeptr;
Nodeptr init(int n){
Nodeptr head = (Nodeptr)malloc(sizeof(Node));
Nodeptr p = head;
head->index = 1;
for(int i = 2;i<=n;i++){
Nodeptr node = (Nodeptr)malloc(sizeof(Node));
node->index = i;
p->next = node;
node->pre = p;
p = node;
}
p->next = head;
head->pre = p;
return head;
}
int main(void){
int m;
cin>>m;
int n;
for(int i = 0;i<m;i++){
cin>>n;
Nodeptr head = init(n);
Nodeptr p;
while(n){
int k = 2;
while((head = head->next)&&--k);
cout<<head->index<<" ";
head->next->pre = head->pre;
head->pre->next = head->next;
p = head;
head = head->next;
free(p);
n--;
}
cout<<endl;
}
return 0;
}