admin管理员组文章数量:1794759
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; }运行结果:
版权声明:本文标题:C语言入门常写的三个代码 内容由林淑君副主任自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.xiehuijuan.com/baike/1687020877a129163.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论