C程序设计谭浩强版个人存档处

C程序设计谭浩强版个人存档处
如有错误请大家指正,谢谢!

第二章习题


2.4(2)

依次将十个数输入,要求输出其中最大的数

#include<stdio.h>
int main(){
    int a,i,max;
    i=0;
    do{scanf("%d",&a);
    if(i==0){
        max=a;
        i++;continue;
    }
    if(i>0){
        if(a>max){
        max=a;i++;continue;
        }
        if(max>=a){
            i++;continue;
        }
    }
    }while(i<10);
    printf("最大值为%d",max);
    return 0;
} 


2.4(3)

有三个数a、b、c,要求按大小顺序将它们输出

#include<stdio.h>
int main(){
	int a,b,c,t;
	scanf("%d %d %d",&a,&b,&c);
	if (a>b)
		{t=a;
		a=b;
		b=t;}
	if (a>c)
	    {t=a;
	    a=c;
	    c=t;}
	if (b>c)
	    {t=b;
	    b=c;
	    c=t;}
	printf("%d %d %d",a,b,c);
	

一、实现思路,用伪代码写出解此题的算法:

1、if a>b 将a和b对换 (a是a,b中的小者)。

2、if a>c 将a和c对换 (a是a,c中的小者,因此a是三者中最小者)。

3、if b>c 将b和c对换 (b是b,c中的小者,也是三者中次小者)。


2.4(4)

求一加到一百

#include<stdio.h>
int main(){
	int i,a;
	for(i=1;i<101;i++)
	{
		a+=i;
	}
	printf("%d",a);
} 

该代码是错误的:输出了5051

a没有初始化
没写return 0;

正确代码为:

#include<stdio.h>
int main(){
	int i,a=0;
	for(i=1;i<101;i++)
	{
		a+=i;
	}
	printf("%d",a);
	return 0;
} 

2.4(5)

判断一个数能否同时被3和5整除

#include<stdio.h>
int main(){
	int a;
	scanf("%d",&a);
	if(a%3==0&&a%5==0){
	printf("%d is a number can be  divided with no remainder by both 3 and 5",a);
	}
	else
	printf("%d isn't a number can be  divided with no remainder by both 3 and 5",a);
	return 0;
} 

2.4(6)

将100-200之间的素数输出

#include<stdio.h>
int main(){
	int i,z,s=1;
	for (i=100;i<=200;i++){
	s=1;
	for (z=2;z<i;z++){
		if(i%z==0)
		{s=0;break;
		}
	}
	if(s!=0){
			printf("%d ",i);
		}
	}
	return 0;
} 


参考博主la garry
注意printf的位置!!!


2.4(7)

求两个数m和n的最大公约数

#include<stdio.h>
 int main(){
 	int m,n;
 	scanf("%d %d",&m,&n);
 	int reminder;
 	reminder=m%n;
 	int x;
 	x=m*n;
 	if (reminder==0){
 		printf("%d %d",n,x/n);
	 }
	else{
		while(reminder!=0){
			m=n;
			n=reminder;
			reminder=m%n;
		}
		printf("%d %d",n,x/n);
	}
 	return 0;
 }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值