sizeof()与strlen()的区别
#include <stdio.h>
#include <string.h> //提供strlen()函数原型
#define DENSITY 62.4 //人体密度(单位:磅/立方英尺)
int main(void)
{
float weight, volume;
int size, letters;
char name[32]; //name是一个可以容纳40个字符的数组
printf("Hi! what's your first name?\n");
scanf("%s", &name);
printf("%s,what's your weight in pound?\n", name);
scanf("%f", &weight);
size = sizeof name;
letters = strlen(name);
volume = weight / DENSITY;
printf("Well,%s,your volume is %1.2f cubic feet.\n", name, volume);
printf("Also,your first name has %d letters,\n, letters", letters);
printf("and we have %d bytes to store it.\n", size);
printf("%d\n", strlen(name));
return 0;
}
/*
所得结果如下:
Hi! what's your first name?
shen
shen,what's your weight in pound?
60
Well,shen,your volume is 0.96 cubic feet.
Also,your first name has 4 letters,
, lettersand we have 32 bytes to store it.
4
*/
从上述我们可以看出strlen()得到的结果是4,而sizeof()得到的值是32.
总结得出:strlen()只算出当前有效用来存储的字符个数,而sizeof()取得的值是数组有多少个存储单位。
while循环
1.执行流程
格式:while(表达式)
语句;
2.可以和for循环相互转化
***for(1; 2; 3)
A;
等价于
while(2)
{
A;
3;
}*
举例回文数
#include <stdio.h>
int main(void)
{
int i, val, sum;
sum = 0;
printf("请输入数字:");
scanf("%d", &val);
i = val;
while(i)
{
sum = sum*10 + i%10;
i /= 10;
}
if (sum ==val)
printf("Y\n");
else
printf("N\n");
return 0;
}
/*
输出结果:
请输入数字:1331
Y
请输入数字:12321
Y
请输入数字:223
N
*/
do……while….循环主要作用于人机交互
int main(void)
{
double a, b, c;
double delat;
double x1, x2;
char ch;
do
{
printf("请输入你所求的一元二次方程系数:\n");
printf("a = ");
scanf("%lf", &a);
printf("b = ");
scanf("%lf", &b);
printf("c = ");
scanf("%lf", &c);
delat = b*b - 4*a*b;
if(delat > 0)
{
x1 = (-b - sqrt(b*b - 4*a*c)) / 2*a;
x2 = (-b + sqrt(b*b - 4*a*c)) / 2*a;
printf("有两个解x1= %lf, x2 = %lf",x1 ,x2);
}
else if (delat == 0)
{
x1 = x2 = (-b) / 2*a;
printf("有一个解x1=x2=%lf", x1);
}
else
printf("没有实数解");
printf("请问还要继续吗Y/N\n");
scanf(" %c", &ch);
}while('y' == ch || 'Y' == ch);
return 0;
}
/*
请输入你所求的一元二次方程系数:
a = 1
b = 5
c = 6
有两个解x1= -3.000000, x2 = -2.000000请问还要继续吗Y/N
y
请输入你所求的一元二次方程系数:
a = 5
b = 5
c = 5
没有实数解请问还要继续吗Y/N
Y
请输入你所求的一元二次方程系数:
a = 2
b = 3
c = 3
没有实数解请问还要继续吗Y/N
n
*/
伪代码scanf()
scanf()可以赋值成功之后将会返还1,失败返还0
#include <stdio.h>
int main(void)
{
int i, j;
i= scanf("%d", &j);
printf("%d\n", i);
return 0;
}