最大公约数HCF与最小公倍数LCM
cpp
#include<stdio.h>
int main(){
int n1,n2,i,hcf,lcm;
printf("Enter two numbers:");
scanf("%d %d",&n1,&n2);
for(i = 1;i <= n1 & i <= n2;i++){
if(n1 % i == 0 & n2 % i == 0){
hcf = i;
lcm = (n1*n2)/hcf;
}
}
printf("HCF of %d and %d is %d\n",n1,n2,hcf);
printf("LCM of %d and %d is %d",n1,n2,lcm);
}
简单实现开根号 sqrt
cpp
#include<stdio.h>
#include<math.h>
int main(){
int a = 9;
int b;
b = sqrt(a);
printf("%d",b);
return 0;
}
计算ax²+bx+c=0的根
cpp
#include<stdio.h>
#include<math.h>
int main(){
double a,b,c,disc,x1,x2,p,q;
printf("Enter ax²+bx+c of a b c:");
scanf("%lf %lf %lf",&a,&b,&c);
disc = b*b - 4*a*c;
if(disc<0){
printf("This equation hasn't real root\n");
}
else{
p = -b/(2.0*a);
q = sqrt(disc)/(2.0*a);
x1 = p + q;
x2 = p - q;
printf("x1 = %5.2f\nx2 = %5.2f\n",x1,x2);
}
return 0;
}
通过分数评判等级
cpp
#include<stdio.h>
int main(){
int s,score;
scanf("%d",&score);
printf("Your grade is:");
s = score/10;
switch(s){
case 1: printf("D");
break;
case 2: printf("D");
break;
case 3: printf("D");
break;
case 4: printf("D");
break;
case 5: printf("D");
break;
case 6: printf("C");
break;
case 7: printf("C");
break;
case 8: printf("B");
break;
case 9: printf("A");
break;
case 10: printf("A");
break;
default:printf("Error");
}
return 0;
}
循环嵌套输出矩阵
cpp
#include<stdio.h>
int main(){
int i,j,n=0;
for(i = 1;i <= 4;i++)
for(j = 1;j <= 5;j++,n++){
if(n%5 == 0)printf("\n");
printf("%d\t",i*j);
}
printf("\n");
return 0;
}
求100-200的全部素数
cpp
#include<stdio.h>
#include<math.h>
int main(){
int n,k,i,m=0;
for(n = 101;n <= 200;n = n+2){ // 偶数不用排查
k = sqrt(n);
for(i = 2;i <= k;i++){
if(n % i == 0)
break;
}
if(i >= k + 1){ // 表示n未被整除
printf("%d ",n);
m = m + 1;
}
if(m % 10 == 0) // 一行内输出10个素数
printf("\n");
}
printf("\n");
return 0;
}
大写字母转小写
cpp
#include<stdio.h>
int main(){
char c1,c2;
printf("Enter a capital letter :");
c1 = getchar();
c2 = c1 + 32;
printf("It's small lettter is :");
putchar(c2);
return 0;
}
计算字符串长度
调用内置函数strlen
cpp
#include<stdio.h>
#include<string.h>
int main(){
char str[50];
int len;
printf("Enter a string:");
scanf("%s",str);
len = strlen(str);
printf("Lengh of '%s' = %d",str,len);
return 0;
}
使用指针
cpp
#include<stdio.h>
int str_len(char* str){
int count = 0;
while(*str != '\0'){
count++;
str++;
}
return count;
}
int main(){
char str[50];
printf("Enter a string:");
scanf("%s",str);
int len = str_len(str);
printf("%d",len);
return 0;
}