希望程序实现从键盘输入4个整数a、b、c、d,将它们按从小到大排序,并输出结果。不知道程序哪里错了
printf里面不要加&,输出变量值的时候不是用&d,用%d进行格式化输出
修改代码
#include <stdio.h>
int main() {
int a, b, c, d;
int temp;
scanf("%d %d %d %d", &a, &b, &c, &d);
if (a > b) {
temp = a;
a = b;
b = temp;
}
if (a > c) {
temp = a;
a = c;
c = temp;
}
if (a > d) {
temp = a;
a = d;
d = temp;
}
if (b > c) {
temp = b;
b = c;
c = temp;
}
if (b > d) {
temp = b;
b = d;
d = temp;
}
if (c > d) {
temp = c;
c = d;
d = temp;
}
printf("%d,%d,%d,%d", a, b, c, d); //用%d
return 0;
}
#include <stdio.h>
int main() {
int a, b, c, d;
int temp;
scanf("%d %d %d %d", &a, &b, &c, &d);
if (a > b) {
temp = a;
a = b;
b = temp;
}
if (a > c) {
temp = a;
a = c;
c = temp;
}
if (a > d) {
temp = a;
a = d;
d = temp;
}
if (b > c) {
temp = b;
b = c;
c = temp;
}
if (b > d) {
temp = b;
b = d;
d = temp;
}
if (c > d) {
temp = c;
c = d;
d = temp;
}
printf("%d,%d,%d,%d", a, b, c, d);
return 0;
}
#include <stdio.h>
int main() {
int a, b, c, d;
printf("请输入4个整数:\n");
scanf("%d %d %d %d", &a, &b, &c, &d);
//冒泡排序
int temp;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3 - i; j++) {
if (a[j] > a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
printf("排序后的结果为:%d %d %d %d\n", a, b, c, d);
return 0;
}
首先定义4个整数变量a、b、c、d,用于存储从键盘输入的4个整数。
输入4个整数,使用scanf函数,将输入的值依次赋值给变量a、b、c、d。
采用冒泡排序,将4个整数从小到大排序。
输出排序后的结果。
注意:
冒泡排序的原理是比较相邻的两个数,如果前面的数大于后面的数,则交换这两个数的位置。这样一趟下来,最大的数就会被移到最后面。依次进行多趟排序,直到所有的数都被排序好。
在冒泡排序中,需要使用临时变量temp,用于交换两个数的位置。
#include <stdio.h>
int main()
{
float a,b,c,t;
printf("请输入三个数:");
scanf("%f,%f,%f",&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("%5.2f,%5.2f,%5.2f",a,b,c);
return 0;
}
运行的结果如下: