zoukankan      html  css  js  c++  java
  • C:冒泡排序&判断一个数是否为素数&求平方根的迭代公式

    冒泡排序

    #include<stdio.h>
    int main ()
    {
        int i,j,n,temp,a[10];
        scanf("%d",&n);
        printf("The original numbers:
    ");
        for(i=0;i<n;i++)
            scanf("%d",&a[i]);
        for(i=0;i<n-1;i++)
            for(j=1;j<n-1;j++)
        if(a[j-1]>a[j])
        {
            temp=a[j-1];a[j-1]=a[j];a[j]=temp;
        }
        printf("
    The sorted number:
    ");
        for(i=0;i<n;i++)
            printf("%d ",a[i]);
        return 0;
    }
    

     判断素数: 

    一个数若可以进行因数分解,那么分解时得到的两个数一定是一个小于等于sqrt(n),一个大于等于sqrt(n),
    若sqrt(n)左侧找不到约数,那么右侧也一定找不到约数。

    #include<stdio.h>
    void main()
    {
    int i,n;
    printf("请输入n:");
    scanf("%d",&n);
    i=2;
    while(i<n)
    {
    if(n%i==0)
    break;
    i++;
    }
    if(i==n)
    printf("%d is prime
    ",n);
    else
    printf("%d is no prime
    ",n);
    }
    

      

    求平方根的迭代公式为:x n+1 = (xn + a / xn) / 2

    #include <stdio.h>
    #include <math.h>
    int   main()
    {
        float a;     
        float x0, x1;
        printf("Input a positive number:
    ");
        scanf("%f", &a);
        x0 = a / 2;  
        x1 = (x0 + a / x0) / 2;
        while (fabs(x1 - x0) >= 1e-5)
        {
            x0 = x1;
            x1 = (x0 + a / x0) / 2;
        }
        printf("The square root of %5.2f is %8.5f
    ", a, x1);
        return 0;
    }
    

      

  • 相关阅读:
    js 与或运算符 || && 妙用(great!!!)
    type of && undefined
    全新框架?微信小程序与React Native的异同之处
    JS-十五章(15.16)
    JS-第十三章
    ValueError: zero-size array to reduction operation maximum which has no identity
    time
    模块
    day8-函数
    day7-format字符串格式化
  • 原文地址:https://www.cnblogs.com/GH-D/p/8087787.html
Copyright © 2011-2022 走看看