zoukankan      html  css  js  c++  java
  • C和指针 第四章 习题

     4.1正数的n的平方根可以通过:

    ai+1= (a+ n / a) / 2

      得到,第一个a1是1,结果会越来越精确。

    #include <stdio.h>
    
    int main() 
    {
    	double input;
    	double exp;
    	scanf_s("%lf", &input);
    
    	double aBefore = 1;
    	double aNow = (aBefore + input / aBefore) / 2;
    
    	exp = aBefore - aNow;
    	exp = exp < 0 ? -exp : exp;
    	printf("aBefore: %lf, aNow: %lf, exp: %f
    
    ", aBefore, aNow, exp);
    	while (exp > 0.000001) {
    		aBefore = aNow;
    		aNow = (aBefore + input / aBefore) / 2;
    		exp = aBefore - aNow;
    		exp = exp < 0 ? -exp : exp;
    		printf("aBefore: %lf, aNow: %lf, exp: %lf
    ", aBefore, aNow, exp);
    	}
    
    	return 0;
    }
    

      

    4.2 打印100以内的质数

      因为2* 50 和 50 *2一样,如果按照1 2 3 4 一直遍历到目标的数其实有很多重复,事实上只需要计算到这个数的平方根即可停止。

      

    #include <stdio.h>
    #include <math.h>
    
    #define TRUE 1
    #define FALSE 0
    
    int isPrimer(int num)
    {
    	int idx;
    	int end = floor(sqrt(num)) + 1;
    	for (idx = 2; idx <= end ; idx++)
    	{
    		if (num % idx == 0) {
    			return FALSE;
    		}
    	}
    	return TRUE;
    }
    int main() 
    {
    	int num;
    	for (num = 1; num <= 100; num++)
    	{
    		if (isPrimer(num)) {
    			printf("%d ", num);
    		}
    	}
    
    	return 0;
    }
    

      

    4.7去除字符串中多余的空格

    #include <stdio.h>
    
    void trim(char str[])
    {
    	//判断之前是否在空格中
    	int inEmpty = 0;
    	//字符串下标
    	int idx = 0;
    
    	//循环字符串
    	while (str[idx] != '') {
    		//遇到空格
    		if (str[idx] == ' ' || str[idx] == '	' || str[idx] == '
    ') {
    			//如果之前不是空格,设置空格状态为1
    			if (!inEmpty) {
    				inEmpty = 1;
    				idx++;
    			}else{
    				//如果之前是空格将之后的字符全部前移一位
    				int len = strlen(str);
    				for (int movStart = idx; movStart <= len; movStart++) {
    					str[movStart] = str[movStart + 1];
    				}
    			}
    		}else {
    			//没遇到空格需要恢复非空格状态
    			inEmpty = 0;
    			idx++;
    		}
    	}
    }
    
    int main()
    {
    	char name[] = "  this is my           name";
    	printf("%s
    ", name);
    	trim(name);
    	printf("%s
    ", name);
    
    	return 0;
    }
    

      

  • 相关阅读:
    Running ROS on Windows 10
    Roomblock: a Platform for Learning ROS Navigation With Roomba, Raspberry Pi and RPLIDAR(转)
    Understand:高效代码静态分析神器详解(转)
    VMware下ubuntu与Windows实现文件共享的方法
    Install rapyuta client on Ubuntu14.04
    Install rapyuta client on Raspberry Pi
    Installing ROS Indigo on the Raspberry Pi
    Shrinking images on Linux
    How to emulate a Raspberry Pi on your PC
    Remastersys打包你自己的ubuntu成iso文件
  • 原文地址:https://www.cnblogs.com/yangxunwu1992/p/5769164.html
Copyright © 2011-2022 走看看