
C语言入门常写的三个代码
今天我们要看的是C语言常写的三个代码。
进行优化:是i按奇数增加。
#include<stdio.h> int main() { int i=0; int count=0; for(i=101;i<=200;i+=2) { //判断i是否为素数 int j=0; for(j=2;j<i/2;j++) { if(i%j==0) break; } if(j>=i/2) { count++; printf("%d ",i); } } printf("\\ncount=%d\\n",count); return 0; }进一步优化:i开平方,减少循环次数。
#include<stdio.h> int main() { int i=0; int count=0; for(i=101;i<=200;i+=2) { //判断i是否为素数 int j=0; for(j=2;j<sqrt(i);j++) { if(i%j==0) break; } if(j>sqrt(i)) { count++; printf("%d ",i); } } printf("\\ncount=%d\\n",count); return 0; }运行结果:
2.打印乘法口诀表
#include<stdio.h> int main() { int i=0; int j=0; int m=0; for(i=1;i<=9;i++) { for(j=1;j<=i;j++) { printf("%d*%d=%2d ",i,j,i*j); } printf("\\n"); } return 0; }运行结果: 注意:打印乘法口诀表要注意最后要换行,且间隔可用%2d使其右对齐。
3.打印1000~2000之间的闰年
#include<stdio.h> int main() { int year = 0; int count = 0; for (year = 1000; year <= 2000; year++) { if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) { printf("%d ", year); count++; } } printf("\\ncount=%d\\n", count); return 0; }运行结果:
👁️ 阅读量:0
© 版权声明:本文《C语言入门常写的三个代码》内容均为本站精心整理或网友自愿分享,如需转载请注明原文出处:https://www.zastudy.cn/wen/1687021105a418513.html。