您的位置:首页 > 其它

字符串和格式化输入/输出

2016-12-22 20:24 211 查看
一、字符串简介

字符串是一个或多个字符的序列。

C的字符串通常以空字符结尾。

#include<stdio.h>

#include<string.h>                    //头文件包含了许多字符串相关的函数原型

#defineDENSITY 62.4             //编译预处理

intmain()

{

    float weight,volume;

    int size,letters;

    char name[40];                      //定义一个字符串类型的数组

    printf("Hi!What's your firstname?\n");

    scanf("%s",name);

    printf("%s,what's your weight inpounds?\n",name);

    scanf("%f",&weight);

    size = sizeof name;                    //sizeof是给出数组的总长度

    letters = strlen(name);                //strlen是给出字符串中的字符个数

    volume = weight / DENSITY;

    printf("Well,%s,your volume is %2.2fcubic feet.\n",name,volume);

    printf("Also,your first name has %dletters,\n"letters);

    printf("and we have %d bytes to storeit in.\n",size);

    return 0;

}

 

注意:scanf()在读取输入时遇到空格、tab、换行处就会停止读取

 

二、常量和C预处理

1.#define

#include<stdio.h>

#definePI 3.14159                        //编译预处理

intmain()

{

    float area,circum,radius;

    printf(""What is the radious ofyour pizza?\n);

    scanf("%f",&radius);

    area = PI * radius * radius;

    circum = 2.0 * PI * radius;

    printf("Your basic pizza parametersare as follows:\n");

    printf("circumference = %1.2f,area =%1.2f\n",circum,area);

    return 0;

}

符号常量所用的名字必须满足变量命名规则,即可以使用大写字母、数字、下划线字符,第一个字符不能是数字。且符号后的所有内容都被用来代替它。 

2.Const

可以使用const关键字把一个变量声明转换成常量声明:

Const int MONTHS = 12   //即MONTHS是代表12的符号常量

3.整数和浮点数限制

#include<stdio.h>

#include<limits.h>          //整数限制

#include<float.h>           //浮点数限制

intmain()

{

    printf("Some number limits for thissystem:\n");

    printf("Biggest int: %d\n",INT_MAX);                                              //int型最大值

    printf("Smallest unsignedlong:%11d\n",LLONG_MIN);                  //long型最小值

    printf("One byte = %d bits on thissystem.\n",CHAR_BIT);            //一个char位数

    printf("Largest double:%e\n",DBL_MAX);                                      //float型最大值

    printf("Smallest normal float:%e\n",FLT_MIN);                              //最小值

    printf("float precision = &ddigits\n",FLT_DIG);                               //最少有效数字位数

         printf("float epsilon =%e\n",FLT_EPSILON);                            //1.00和比1.00大的最小的float之间的差值

    return 0;

}

三、输入输出函数

输出:

#include<stdio.h>

#definePAGES 931

intmain()

{

    printf("*%d*\n",PAGES);             //字段相同

    printf("*%2d*\n",PAGES);           //宽度为2的字段,自动适应

    printf("*%10d*\n",PAGES);         //宽度为10的字段,且数字位于右端

    printf("*%-10d*\n",PAGES);        //宽度为10的字段,且数字位于左端

    return 0;

}

 

小数点后的数自动四舍五入

    printf("*%10.3f*\n",RENT);         //宽度为10的字段,小数点后3位

    printf("*%10.3e*\n",RENT);        //宽度为10的字段,小数点后3位,结果为:* 3.863e+03*

    printf("*%+4.3f*\n",RENT);         //带符号的输出

    printf("*%f010.2*\n",RENT);       // 0填充前导字段 结果:*0003852.99*
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: