#include<stdio.h>
int main(void){ long num;long sum = 0L;int status;printf("Please enter an integer to be summed: ");
printf("(q to quit)");while((status = scanf("%ld",&num)) == 1) //==运算符的优先级比=要高
{ sum = sum +num;printf("Please enter next integer(q to quit):"); }printf("Those integer sum to %ld.\n",sum);
return 0; }--浮点数的比较/*浮点数比较中只能使用大于和小于号。原因在于舍入误差可能造成两个逻辑上应该相等的数不相等了。例如:3和1/3的乘积应该是1.0,但是您用6位小数表示1/3,乘积就是.999999而不是1
*/
#include<math.h>
#include<stdio.h>int main(void){ const double ANSWER = 3.14159;double response;printf("What is the value of PI?\n");scanf("%lf",&response);while(fabs(response - ANSWER) > 0.0001){ printf("Try again!\n");scanf("%lf",&response);}printf("Close enough!\n");return 0;}//真表达式的值为1,而假表达式的值为0
#include<stdio.h>
int main(void){ int n = 3;while(n)
printf("%2d is true\n",n--);printf("%2d is false\n",n);n = -3;
while(n)printf("%d is true\n",n++);printf("%2d is false\n",n);return 0;}
/* C中_Bool类型在C99中提供了一个stdbool.h的头文件,可以使用bool来代替_Bool,并把true和false定义为1和0的符号常量,包含这个头文件可以写出与c++兼容的代码,因为c++把bool、true、false定义为关键字*/ //字符代替数字来计数#include<stdio.h>int main(void){ char ch;
for(ch = 'a'; ch <= 'z';ch++)
printf("The ASCII value for %c is %d.\n",ch,ch);return 0;
}
逗号运算符:
/*1.逗号是个顺序点,逗号左边产生的所有副作用都在程序运行到逗号右边之前生效2.整个逗号表达式的值是右边成员的值x = (y=3,(z = ++y +2)+5); x = 11
houseprice = 249,500;
houseprice = 249 是左表达式,而500是有表达式houseprice =(249,500);
把houseprice赋值为500,因为该值是右表达式的值*/
//使内部循环依赖于外部循环的嵌套循环
#include<stdio.h>int main(void){ const int ROWS = 6;const int CHARS = 6;int row;char ch;for(row = 0;row < ROWS;row++)
{ for(ch = ('A'+row); ch < ('A' +CHARS);ch++)printf("%c",ch);printf("\n");
}return 0;
}
数组--线性存储的一系列相同类型的值
小技巧:可以用#define指令创建一个指定数组大小的明显常量,方便以后改动。
//以下是一个计算数值的整数次幂的程序
#include<stdio.h>
double power (double n,int p);int main(void){ double x,xpow;int exp;printf("Enter a number and the position integer power");
printf(" to which\nthe number will be raised. Enter q to quit.\n");while(scanf("%lf%d",&x,&exp)==2)
{ xpow = power(x,exp);printf("%.3g to the power %d is %.5g\n",x,exp,xpow);printf("Enter next pair of numbers or q to quit.\n");}printf("Hope you enjoyed this power trip -- bye!\n");
return 0;}double power(double n,int p)
{ double pow = 1;int i;for(i = 1; i <= p; i++)
pow *=n;return pow;
}