C语言入门的一些基本资源推荐和程序语法概览

2020-01-06 14:06:08刘景俊

1. 使用 bool 变量


#include <stdio.h>
#include <stdbool.h>
int main(void)
{
  float input;
  bool isTrue=(scanf("%f",&input)==1);
  while(isTrue){
    printf("you typed %.dn",(int)input);  //强制类型转换
    isTrue=(scanf("%f",&input)==1);
  }
  return 0;
}

2. 字符


#include <stdio.h>
#include <stdlib.h>
int main()
{
  char beep;  //与 int beep; 等效
  while(scanf("%c",&beep)==1){
    printf("you typed a %c n", beep);
  }
  //scanf 会将回车符一起读进变量,最后结果不能达到预期!可采用后面一种方法
  return 0;
}

#include <stdio.h>
#include <stdlib.h>
int main()
{
  char beep;
  while(gets(&beep)){
    printf("you typed a %c n", beep);
  }
  return 0;
}

3. 常量


#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <float.h>
#define PI 3.1416
#define TEXT "hello world"
#define HTML 'H'
int main()
{
  //常量定义 以及C预处理器 系统预定义常量
  const int china =345;
  printf("%d ,%d ,%d ,%dn", INT_MAX, china, FLT_MAX_10_EXP, CHAR_MIN);
}

4. 数学函数


#include <stdio.h>
#include <math.h>
#define PI 3.1415926
void main(void)
{
  //i 为第几行,画余弦曲线
  int i, j, blankNUm;
  float cosValue;
  for(i=0;i<21;i++){
    cosValue =1-i/10.0;
    blankNUm =(int)(180/5/PI*acos(cosValue));

    for(j=0;j<blankNUm;j++)
      printf("");
    printf("*");
    for(j=0;j<(73-2-2*blankNUm);j++)
      printf("");
    i!=20?printf("*n"):printf("");
  }
  return 0;
}


#include <stdio.h>
int main(void)
{
  //计算 e ,前50项,其实根前10项结果一样,只是为了演示,用double可以满足精度要求
  int i;
  double factorial=1.0, e=0;
  for(i=1;i<=50;i++){
    factorial*=i;
    e+=1.0/factorial;
  }
  printf("%f n",e);
  return 0;
}

5. 特殊字符


#include <stdio.h>
#include <stdlib.h>
int main()
{
  float salary;

  printf("aplease enter you salary by month:");  // a响龄,貌似
  printf(" $______bbbbbb");  // b退格
  if(scanf("%f",&salary)==1){
    printf("t$%.2f per manth is $%.2f per year", salary, salary*12.0);
    printf("rgEE!wa hn");  // r使光标移到当前行的起始位置,这里很微妙噢
  }
    
  return 0;
}

/* please enter you salary by month: $23.4__ */
/* gEE!wa h$23.40 per manth is $280.80 per year */