您的位置:首页 > 编程语言 > C语言/C++

4. 29 C语言 程序结构-初级

2015-05-20 01:03 316 查看
printf 函数中的格式转化字符及其含义



格式转换符

含义

对应的表达式数据类型

%d 或 %i

以十进制形式输出一个整型数据

有符号整数

%x 或 %X

以十六进制格式输出一个无符号整型数据

无符号整数

%o

以八进制格式输出一个无符号整型数据

无符号整数

%u

以十进制格式输出一个无符号整型数据

无符号整数

%c

输出一个字符型数据

字符型

%s

输出一个字符串

字符串

%f

以十进制小数形式输出一个浮点型数据

浮点型

%e 或 %E

以指数形式输出一个浮点型数据

浮点型

%g 或 %G

自动选择合适的形式输出数据

浮点型

%p

以主机的格式显示指针

指针类型

另外,可以在格式转换字符和%之间插入一些辅助的格式控制字符。因此,格式控制字符的一般格式为:

%[flag][width][.precision][size]Type

有符号整数的输出

输出有符号整数的格式控制符的一般形式为:

%[-][+][0][width][.precision][l][h]d

其中各控制符的说明如下:

-:表示输出的数据左对齐,默认时是右对齐。

+:输出正数时,在数的前面加上+号。

0:右对齐时,如果实际宽度小于width,则在右边的空位补0。

width:无符号整数,表示输出整数的最小宽度。若实际宽度大于width,则按照实际宽度输出。

precision:无符号整数,表示至少要输出precision位。若整数的位数大于 precision,则按照实际的位数输出,否则在左边的空位上补0。

l:输出长整形数据

h:输出短整形数据



无符号整数的输出

输出无符号整数的格式控制符的一般形式为:

%[-][#][0][width][.precision][l][h]u|o|x|X

其中各控制符的说明如下:

#:当以八进制形式输出数据(%o)时,在数字前输出0;当以十六进制形式输出数据(%x或%X)时,在数字前输出0x或0X。

precision:与前面介绍的相同,但要注意八进制数字前的0和十六进制前的0x或0X同样占位数。

其他字段与前面介绍的相同。



小结:

格式转换符

数据类型

%u

unsigned int

%ld

long

%lx

十六进制表示long

%lo

八进制表示long

%hd

short

%hx

十六进制表示short

%ho

八进制表示short

%lu

unsigned long

%lld

long long

%llu

unsigned long long



实数的输出

输出实数的格式控制符的一般形式为:

%[-][+][#][0][width][.precision][l|L]f|e|E|g|G

其中各控制符的说明如下:

#:必须输出小数点。

precision:规定输出实数时,小数部分的位数。

l:输出double型数据(默认也是输出double型数据)。

L:输出long
double型数据。

其他字段的含义与前面介绍的相同。



字符和字符串的输出

输出字符和字符串的格式控制符的一般形式为:

输出字符:%[-][0][width]c

输出字符串:%[-][0][width][.precison]s

其中各控制符的说明如下:

precision:只输出字符串的前precision个字符。

其他字段的含义与前面介绍的相同。



其它可用的修饰符

标志

意义

(空格)

有符号的值若为正,则显示时带前导空格(但是不显示符号);若为负,则带减号符号。+标志会覆盖空格标志。

示例:"% 6.2f"

*

如果您不想事先指定字段宽度,而是希望由程序来指定该值,那么您可以在字段宽度部分使用*代替数字来达到目的,但是您也必须使用一个参数来告诉函数字段宽度应该是什么。(注意在scanf函数中*是另一种含义。)

示例:printf("The number is: %*d.\n", width, number);



使用printf函数要注意一下几点

1. 格式控制字符串后面表达式的个数一般要与格式控制字符串中的格式控制符的个数相等。

2. 输出时表达式值的计算顺序是从右到左。

3. 格式转换符中,除了X、E、G以外,其他均为小写。

4. 表达式的实际数据类型要与格式转换符所表示的类型相符,printf函数不会进行不同数据类型之间的自动转换。

Scanf函数(Wiki):

The formatting placeholders in scanf are
more or less the same as that in printf,
its reverse function.

There are rarely constants (i.e. characters that are not formatting placeholders)
in a format string, mainly because a program is usually not designed to read known data. The exception is one or more whitespace characters,
which discards all whitespace characters in the input.

Some of the most commonly used placeholders follow:

%d : Scan an integer as a signed decimal number.

%i : Scan an integer as a signed number. Similar to %d,
but interprets the number as hexadecimal when
preceded by 0x and octal when
preceded by 0. For example, the string 031 would
be read as 31 using %d, and 25 using %i.
The flag h in %hi indicates
conversion to a short and hh conversion
to a char.

%u : Scan for decimal unsigned
int (Note that in the C99 standard the input value minus sign is optional, so if a minus sign is read, no errors will arise and the result will be the two's
complement of a negative number, likely a very large value. See strtoul().[not
in citation given]) Correspondingly, %hu scans
for an unsigned short and %hhu for
an unsigned char.

%f : Scan a floating-point number
in normal (fixed-point) notation.

%g, %G :
Scan a floating-point number in either normal or exponential notation. %g uses lower-case letters and %G uses
upper-case.

%x, %X :
Scan an integer as an unsigned hexadecimal number.

%o : Scan an integer as an octal number.

%s : Scan a character
string. The scan terminates at whitespace.
A null character is stored at the end of the
string, which means that the buffer supplied must be at least one character longer than the specified input length.

%c : Scan a character (char). No null
character is added.

whitespace:
Any whitespace characters trigger a scan for zero or more whitespace characters.
The number and type of whitespace characters do not need to match in either direction.

%lf : Scan as a double floating-point
number.

%Lf : Scan as a long
double floating-point number.

The above can be used in compound with numeric modifiers and the l, L modifiers
which stand for "long" in between the percent symbol and the letter. There can also be numeric values between the percent symbol and the letters, preceding the long modifiers
if any, that specifies the number of characters to be scanned. An optional asterisk (*)
right after the percent symbol denotes that the datum read by this format specifier is not to be stored in a variable. No argument behind the format string should be included for this dropped variable.

The ff modifier
in printf is not present in scanf, causing differences between modes of input and output. The ll and hh modifiers
are not present in the C90 standard, but are present in the C99 standard.[2]

An example of a format string is

"%7d%s %c%lf"

The above format string scans the first seven characters as a decimal integer, then reads the remaining as a string until a space,
new line or tab is found, then scans the first non-whitespace character following and a double-precision floating-point number afterwards.

课堂练习:



使用do...while...实现银行登录:

设定一个密码

提示用户输入密码

如果用户输入密码错误,提示重新输入,三次均输入错误则提示:Wrong

如果用户输入正确,提示:Correct



#include "stdio.h"



int main(int argc, char const *argv[]){

   

int psw = 999999;

    int inputpsw;

    int i = 0;

    

    do {

        i++;

        printf("Input
password: ");

        scanf("%d",&inputpsw);

        if (psw == inputpsw) {

            printf("Correct.\n");

            break;

        }

        if (i == 3) {

            printf("Wrong.\n");

        }

    } while (i < 3);



    return 0;

}





作业:



1、scanf(),printf()输入输出:

1)输入三角形的三边长,求三角形面积?



#include <stdio.h>

#include <math.h>



int main(int argc, char const *argv[])

{

    int a, b, c;

    

    

    while (1) {

        

        printf("Input
3 lengthes of side: ");

        scanf("%d
%d %d", &a, &b, &c);

    

        int n = a + b > c && a + c > b && b + c > a;

        if (n == 0) {

            printf("Not
a triangle. ");

        }

        else

            break;

    }



    float s = (a + b + c) / 2;

    

    float area = sqrt(s
* (s - a) * (s - b) * (s -c));

    

    printf("Triangle
area = %.2f\n", area);



    return 0;

}



2)输入一个字符,判定该字符为数字、字母、还是特殊符号;



#include <stdio.h>



int main(int argc, char const *argv[])

{

    char x;

    printf("Input
a character:");

    scanf("%c",
&x);

    

    if (x >= '0' && x <= '9') {

        printf("It's
a number\n");

    }else if (x
>= 'A' && x <= 'Z'){

        printf("It's
a letter\n");

    }else if (x
>= 'a' && x <= 'z'){

        printf("It's
a letter\n");

    }else{

        printf("It's
a special symbol.\n");

    }

    return 0;

}

2、选择结构

1)下雨条件,如果输入为‘Y’表示要下雨,输出“下雨了,需要带上雨具!”,反之,输出“没有下雨,不需要带雨具”。(外面下雨了么?Y(yes)/N(no))



#include <stdio.h>



int main(int argc, char const *argv[])

{

    char weather;

    printf("Is it rainning?
");

    scanf("%c",
&weather);

    if (weather == 'Y' || weather == 'y'){

        printf("Yes, take
umbrellar!\n");

    }

    else{

        printf("No, don't
take umbrellar!\n");

    }

    return 0;

}





2)设定一个取伞系统,用户输入一个数字,如果该数为单数,表示外边正在下雨,取伞系统提示用户“下雨了,记得带上带雨具,路上注意安全”;



#include <stdio.h>



int main(int argc, char const *argv[])

{

    int a;

    printf("Input a number:
");

    scanf("%d",
&a);

    

    if (a % 2 != 0) {

        printf("Rainning
outside. Take umbrellar and careful yourselfe.\n");

    }

    return 0;

}



3)设置一个汽车尾号限定程序,提示用户选择1-5(1代表星期一,限行尾号为9;2代表星期二,限行尾号为3;3代表星期三,限行尾号为7;4代表星期四,限行尾号为2;5代表星期五,限行尾号为4)



#include <stdio.h>



int main(int argc, char const *argv[])

{

    

    int a;

    printf("Please in
put 1 ~ 5 \n");

    printf("1 : Monday
\n");

    printf("2 : Tuesday
\n");

    printf("3 : Wednesday
\n");

    printf("4 : Thursday
\n");

    printf("5 : Friday
\n");

    

    scanf("%d",&a);

    

    switch (a) {

        case 1:

            printf("Restrictions
tail number 9\n");

            break;

        case 2:

            printf("Restrictions
tail number 3\n");

            break;

        case 3:

            printf("Restrictions
tail number 7\n");

            break;

        case 4:

            printf("Restrictions
tail number 2\n");

            break;

        case 5:

            printf("Restrictions
tail number 4\n");

            break;

        default:

            printf("Error
input.");

            break;

    }

    return 0;

}





4)使用switch语句计算今年的某一天是今年的第几天(输入月和日)



#include <stdio.h>



int main(int argc, char const *argv[])

{

    

    int month, day;

    int total_day = 0;

    

    printf("Please input
month: \n");

    scanf("%d",
&month);

    

    switch (month-1) {

        case 12:  total_day += 31;

        case 11:  total_day += 30;

        case 10:  total_day += 31;

        case 9:  total_day += 30;

        case 8:  total_day += 31;

        case 7:  total_day += 31;

        case 6:  total_day += 30;

        case 5:  total_day += 31;

        case 4:  total_day += 30;

        case 3:  total_day += 31;

        case 2:  total_day += 28;

        case 1:  total_day += 31;break;

        default:  break;

    }

    

    printf("Please input
day: \n");

    scanf("%d",
&day);

    

    total_day += day;

    if (total_day > 3) {

        printf("It's %dth
day of this year!\n",total_day);

    }

    if (total_day == 1) {

        printf("It's %dst
day of this year!\n",total_day);

    }

    if (total_day == 2) {

        printf("It's %dnd
day of this year!\n",total_day);

    }

    if (total_day == 3) {

        printf("It's %drd
day of this year!\n",total_day);

    }

    return 0;

}







5)某单位马上要加工资,增加金额取决于工龄和现工资两个因素:对于工龄大于等于20年的,如果现工资高于2000,加200元,否则加180元;对于工龄小于20年的,如果现工资高于1500,加150元,否则加120元。工龄和现工资从键盘输入,编程求出一个员工加工资后的工资。



#include <stdio.h>



int main(int argc, char const *argv[])

{

    

    int salary = 0;

    int increseSalary = 0;

    printf("Input your
monthly salary: ");

    scanf("%d",
&salary);

    int working_age = 0;

    printf("Input your
working age: ");

    scanf("%d",
&working_age);

    

    if (working_age >= 20) {

        if (salary > 2000) {

            increseSalary = salary + 200;

        }else {

            increseSalary = salary + 180;

        }

    }else {

        if (salary > 1500) {

            increseSalary = salary + 150;

        }else {

            increseSalary = salary + 120;

        }

    }

    

    printf("Your salary
increased to %d \n",increseSalary );

    return 0;

}





3、循环结构

1)输入一周七天的温度,然后求出该周平均温度并打印



#include <stdio.h>



int main(int argc, char const *argv[])

{

    

    float temp[7];

    int i;

    float sum_temp = 0, average_temp;

    

    for (i = 0; i < 7; i++) {

        printf("Input
a temperature: ");

        scanf("%f",
&temp[i]);

        sum_temp += temp[i];

    }

    

    average_temp = sum_temp / 7;

    printf("The average
temperature of this week: %.2f\n", average_temp);

    

    return 0;

}







2)给定一个数学表达式,然后求出其结果。数学表达式如下所示:

0 – 1 + 2 – 3 + 4 – 5 + 6 …… - 99 + 100



#include <stdio.h>



int main(int argc, char const *argv[])

{

    

    int i;

    int sum = 0;

    int sign = -1;

    

    for (i = 0; i <= 100; i++) {

        

        sign = -sign;

        sum += i * sign;

    }

    printf("sum = %d\n",
sum);

    

    return 0;

}





3)打印出0--10之间偶数,以及这些偶数的平方及立方值



#include <stdio.h>



int main(int argc, char const *argv[])

{

    

    int i;

    int square = 0;

    int cubic = 0;

    

    printf("Even  Squrea 
Cubic\n");

    for (i = 0; i <= 10; ) {

        if (i % 2 == 0) {

            printf("%2d",i);

            square = i * i;

            printf(" %7d
",  square);

            cubic = i * i * i;

            printf(" %6d
", cubic);

        }

        printf("\n");

        i = i + 2 ;

    }

    

    

    return 0;

}





4)输出n个连续的偶数,如 n
= 3,输出 0 2 4



#include <stdio.h>



int main(int argc, char const *argv[])

{

    

    int i = 1, n;

    int k= 0;

    

    printf("How many evens
do you want? ");

    scanf("%d",
&n);

    

    while (i <= n) {

        

        printf("%4d  ",
k);

        if (i % 6 == 0) { //Newline
after printed 6 numbers.

            printf("\n");

        }

        k += 2;

        i++;

    }

    

    printf("\n");

    

    return 0;

}





5)输入两个正整数,求得两个数之间所有整数的和,例如,n1 = 3, n2 = 10;结果sum
= 3 + 4 + 5 + 6…+ 10 = 52;



#include <stdio.h>



int main(int argc, char const *argv[])

{

    

    int n1 , n2;

    int sum = 0;

    

    

    printf("Input two
integers: ");

    scanf("%d %d",
&n1, &n2);

    

    int a, b;

    

    a = n1 < n2 ? n1 : n2;

    b = n1 > n2 ? n1 : n2;

   

    if (a == b) {

        printf("sum =
%d\n", a + b);

    }

    else {

        while (a <= b) {

            sum += a;

            a++;

        }

        printf("sum =
%d\n", sum);

    }

    return 0;

}





6)依次输入几个数据,直到0作为输入的结束,然后求出输入的这些数据的总和及平均值(结束循环,使用break)



#include <stdio.h>



int main(int argc, char const *argv[])

{

    int i = 0;

    float num[20];

    float sum = 0.0f;

    float avg = 0.0f;

    

    printf("Input some
numbers. To end input , use 0\n");



    while (1) {

        scanf("%f",&num[i]);

        if (num[i] == 0) {

            break;

        }

        i++;

    }

    

    for (int j
= 0; j < i; j++) {

        sum += num[j];

    }

    

   

 if (i != 0) {

        avg = sum / i ;

        printf("sum =
%3.2f\n", sum);

        printf("avg =
%3.2f\n", avg);

    }else

        printf("No data
inputed.\n");

    

    

    

    

   return 0;

}







提高题部分:

1)使用do…while循环实现银行登录示例

要求:设定输入的固定密码;

提示用户输入密码;

如果用户输入错误,提示请重新输入,三次均错误,提示用户,“输入失败”;

如果用户输入正确,提示“登录成功”



#include "stdio.h"



int main(int argc, char const *argv[]){

   

int psw = 999999;

    int inputpsw;

    int i = 0;

    

    do {

        i++;

        printf("Input
password: ");

        scanf("%d",&inputpsw);

        if (psw == inputpsw) {

            printf("Correct.\n");

            break;

        }

        if (i == 3) {

            printf("Wrong.\n");

        }

    } while (i < 3);



    return 0;

}





2)预习使用三目运算符,能使用多种方式求出两个数中的最大值;完成后,尝试使用多种方式求出三个数中的最大值;



#include <stdio.h>



int main(int argc, char const *argv[])

{

    int n = 9, m = 20;

    int bigNum = n > m ? n : m;;

    printf("big number:
%d\n", bigNum);

    

    int a = 3, b = 8 , c =15;

    int temp, max;

    temp = (a > b)? a : b;

    max = (temp > c) ? temp : c;

    printf("max number:
%d\n", max);



   return 0;

}





3)Chuckie Lucky赢了100W美元,他把它存入一个每年盈利8%的账户。在每年的最后一天,Chuckie取出10W美元。编写一个程序,计算需要多少年Chuckie就会清空他的账户。



#include <stdio.h>



int main(int argc, char const *argv[])

{

    int spare = 1000000;

    int i = 0;

    

    do{

        spare *= 1.08;

        spare -= 100000;

        i++;

        

    }while (spare > 0);

    

    printf("%d years later,
Chuckie has no money in this account.\n", i);

    

   

    

   return 0;

}





注:根据情况选择题目,也可自行定义题目
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: