C語言入門②
阿新 • • 發佈:2018-10-31
1.給定兩個整形變數的值,將兩個值的內容進行交換。
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> int exchange(int x,int y){ printf("第一個數是:%d\t第二個數是%d\n", x, y); int temp = 0; temp = x; x = y; y = temp; printf("第一個數是:%d\t第二個數是%d\n", x, y); return 0; } int main(){ int a = 0; int b = 0; printf("輸入兩個不同的整數:\n"); scanf("%d %d", &a, &b); exchange(a, b); system("pause"); return 0; }
2.不允許建立臨時變數,交換兩個數的內容(附加題)
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> int exchange(int x,int y){ printf("第一個數是:%d\t第二個數是%d\n", x, y); printf("內容交換:第一個數是:%d\t第二個數是%d\n", y, x); return 0; } int main(){ int a = 0; int b = 0; printf("輸入兩個不同的整數:\n"); scanf("%d %d", &a, &b); exchange(a, b); system("pause"); return 0; }
3.求10 個整數中最大值。
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> int main(){ int a[10],i=0,k=0,temp = 0; printf("輸入十個整數\n"); while (i < 10){ scanf("%d", &a[i]); i++; } for (i = 0; i < 10; i++){ for (int k = i + 1; k < 10; k++){ if (a[i] < a[k]){ temp = a[k]; } } } printf("最大的數是%d", temp); system("pause"); }
4.將三個數按從大到小輸出。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
int main(){
int a[3], i = 0,k=0,temp=0;
for (i = 0; i < 3; i++){
scanf("%d", &a[i]);
}
for(i = 0; i < 3; i++){
for (int k = i + 1; k < 3; k++){
if (a[i] < a[k]){
temp = a[i];
a[i] = a[k];
a[k] = temp;
}
}
}
for (i = 0; i < 3; i++){
printf("%d ", a[i]);
}
system("pause");
}
5.求兩個數的最大公約數。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
int main(){
int a, b, num1, num2, temp;
printf("please input num1 and num2: ");
scanf("%d %d", &num1, &num2);
if (num1 >= num2)
{
a = num1;
b = num2;
}
if (num1 < num2)
{
a = num2;
b = num1;
}
while (b != 0)
{
temp = a % b;
a = b;
b = temp;
}
printf("最大公約數是%d\n", a);
system("pause");
return 0;
}