1. 给定两个整形变量的值,将两个值的内容进行交换。
2. 不允许创建临时变量,交换两个数的内容(附加题)
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
void swap(int *x,int *y)
{
int tmp=*x;
*x=*y;
*y=tmp;
}
int main()
{
int a=10;
int b=20;
swap(&a,&b);
printf("a=%d b=%d\n",a,b);
system("pause");
return 0;
}
void swap(int *x,int *y)
{
*x=*x+*y;
*y=*x-*y;
*x=*x-*y;
}
int main()
{
int a=10;
int b=20;
swap(&a,&b);
printf("a=%d b=%d\n",a,b);
system("pause");
return 0;
}
void swap(int *x,int *y)
{
*x=*x * *y;
*y=*x / *y;
*x=*x / *y;
}
int main()
{
int a=10;
int b=20;
swap(&a,&b);
printf("a=%d b=%d\n",a,b);
system("pause");
return 0;
}
void swap(int *x,int *y)
{
*x=*x^*y;//01010^10100=11110
*y=*x^*y;//11110^10100=01010
*x=*x^*y;//11110^01010=10100
}
int main()
{
int a=10;
int b=20;
swap(&a,&b);
printf("a=%d b=%d\n",a,b);
system("pause");
return 0;
}
3. 求10 个整数中最大值。
int MAX(int arr[],int sz)//数组内容被改掉
{
int i=0;
int max=arr[0];
for(i=1; i<sz; i++)
{
if(arr[i]>max)
{
int tmp=arr[i];
arr[i]=max;
max=tmp;
}
}
return max;
}
int main()
{
int arr[10]={2,3,4,1,5,8,6,7,9,0};
int sz=sizeof(arr)/sizeof(sizeof(arr[0]));
int ret=MAX(arr,sz);
printf("最大的数为:%d\n",ret);
system("pause");
return 0;
}
int MAX(int arr[],int sz)
{
int i=0;
int max=arr[0];
for(i=1; i<sz; i++)
{
if(arr[i]>max)
{
max=arr[i];
}
}
return max;
}
int main()
{
int arr[10]={2,3,4,1,5,8,6,7,9,0};
int sz=sizeof(arr)/sizeof(sizeof(arr[0]));
int ret=MAX(arr,sz);
printf("最大的数为:%d\n",ret);
system("pause");
return 0;
}
比如: 15 0000 1111 4 个 1
程序原型:
int count_one_bits(unsigned int value)
{
// 返回 1的位数
}
int count_one_bits(unsigned int value)
{
int count=0;
int tmp=0;
while(value>0)
{
tmp=value%2;
if(tmp!=0)
{
count++;
}
value/=2;
}
return count;
}
int main()
{
unsigned int value=0;
int count=0;
printf("请输入你要统计的数:");
scanf("%d",&value);
count=count_one_bits(value);
printf("需统计数中一的个数为:%d\n",count);
system("pause");
return 0;
}
通过上面的代码,我们发现它只试用于正数,如果输入负数,则结果错误。
改进代码:
#include<stdio.h>
#include<stdlib.h>
int count_one_bits(int value)
{
int i=0;
int count=0;
for(i=0; i<32; i++)
{
if(((value>>i) && 1) == 1)
{
count++;
}
}
return count;
}
int main()
{
int value=0;
int count=0;
printf("请输入你要统计的数:");
scanf("%d",&value);
count=count_one_bits(value);
printf("需统计数中一的个数为:%d\n",count);
system("pause");
return 0;
}
#include<stdio.h>
#include<stdlib.h>
int count_one_bits(int value)
{
int count=0;
while(value)
{
count++;
value=value&(value-1);
}
return count;
}
int main()
{
int value=0;
int count=0;
printf("请输入你要统计的数:");
scanf("%d",&value);
count=count_one_bits(value);
printf("需统计数中一的个数为:%d\n",count);
system("pause");
return 0;
}