C++练习-函数

double dist( double x1, double y1, double x2, double y2 ){
    double Dx,Dy;
    Dx=fabs(x1-x2);
    Dy=fabs(y1-y2);
    double dis;
    dis=sqrt(pow(Dx,2)+pow(Dy,2));
    return dis;
}
int sign( int x ){
    int res;
    if(x>0){
        res=1;
    }
    else if(x==0){
        res=0;
    }
    else{
        res=-1;
    }
    return res;
}
double fact(int n){
    double res=1;
    for(int i=1;i<=n;i++){
        res*=i;
    }
    return res;
}
int IsSquare(int n) {
    if (n < 0) return 0;
    
    int root = (int)sqrt(n);
    return (root * root == n) || ((root + 1) * (root + 1) == n);
}
int prime(int p){
    if(p<=1){
        return 0;
    }
    if(p == 2){
        return 1;  // 2是素数
    }
    if(p % 2 == 0){
        return 0;  // 偶数(除了2)都不是素数
    }
    for(int i=3;i*i<=p;i+=2){
        if(p%i==0){
            return 0;
        }
    }
    return 1;
}
int PrimeSum(int m,int n){
    int sum=0;
    for(int i=m;i<=n;i++){
        if(prime(i)){
            sum+=i;
        }
    }
    return sum;
}
#include <stdio.h>
void pyramid(int n){
   for(int i=1;i<=n;i++){
    for(int j=0;j<(n-i);j++){
        printf(" ");
    }
    for(int j=1;j<=i;j++){
        printf("%d",i);
        printf(" ");
    }
    printf("\n");
   } 
}
int gcd(int x, int y) { 
    while (y != 0) {
        int temp = y;
        y = x % y;
        x = temp;
    }
    return x;
}
int CountDigit(int number,int digit){
    int res=0;
    char str[20];
    sprintf(str,"%d",number);
    for(int i=0;i<20;i++){
        if(str[i]-'0'==digit){
            res++;
        }
    }
    return res;
}
int func(int x){
    if(x==0){
        return 1;
    }
    int res=1;
    for(int i=1;i<x;i++){
        res*=i;
    }
    return res;
}

double funcos(double e,double x){
    double res=0;
    int temp=0;
    int counter=0;
    while(pow(x,counter)/func(counter)<e){
        temp=pow(x,counter)/func(counter)<e;
        res+=temp*pow(-1,counter/2);
        counter+=2;
    }   
    return res;
}

//13.9提交后显示有错误,暂时不知道具体原因,尚未修改

int func(int x){
    if(x==0){
        return 1;
    }
    int res=1;
    for(int i=1;i<x;i++){
        res*=i;
    }
    return res;
}

double funcos(double e,double x){
    double res=0;
    int temp=0;
    int counter=0;
    while(pow(x,counter)/func(counter)<e){
        temp=pow(x,counter)/func(counter)<e;
        res+=temp*pow(-1,counter/2);
        counter+=2;
    }   
    return res;
}

 

posted @ 2025-10-29 23:38  bluepoet  阅读(12)  评论(0)    收藏  举报