[英]I am trying to arrange three 3 numbers in ascending manner using if statement, but this doesn't work for the third number. What can be done about it?
#include <stdio.h>
int main()
{
int a, b, c, temp;
scanf("%d %d %d", &a, &b, &c);
if (a > b)
{
temp = a;
a = b;
b = temp;
}
else if (b > c)
{
temp = b;
b = c;
c = temp;
}
else if (c > a)
{
temp = c;
c = a;
a = temp;
}
printf("%d %d %d", a, b, c);
return 0;
}
如果我输入8,6,3,则输出为6,8,3。 它不会更改最后一个数字。 我正在尝试使用if语句以升序方式排列三个3号,但这不适用于第三个数字。 该怎么办?
最简单的方法是先找到最小的,然后确保其余两个正确:
int main()
{
int a, b, c, temp;
int ret = scanf("%d %d %d", &a, &b, &c);
if (ret != 3) {
printf("scanf() error\n");
exit(1);
}
// get smallest into a
if ((b < a) && (b < c)) {
temp = a;
a = b;
b = temp;
} else if ((c < a) && (c < b)) {
temp = a;
a = c;
c = temp;
}
// a is smallest, check b and c
if (c < b) {
temp = b;
b = c;
c = temp;
}
printf("%d %d %d", a, b, c);
return 0;
}
else if
要比较a与b,b与c和a与c(这三个,而不仅仅是其中一个), if
需要使用if
而不是else if
。 此外,在移动数字时,必须考虑它们的位置,以便进行最后的比较。 而你的第三个条件是错误的。 因此,这应该是您要尝试执行的操作:
#include <stdio.h>
int main(){
int a, b, c, temp;
scanf("%d %d %d", &a, &b, &c);
if (a > b){
temp = a;
a = b;
b = temp;
}
if (b > c){
temp = b;
b = c;
c = temp;
if (a > b){
temp = a;
a = b;
b = temp;
}
}
else if (a > c){
temp = c;
c = a;
a = temp;
}
printf("%d %d %d", a, b, c);
return 0;
}
我认为您误解了if else if结构的概念,在您的情况下,它不适用于第三个数字,因为仅当if条件为false时,if部分的执行才能到达else。
#include <stdio.h>
int main()
{
int a,b,c,temp;
scanf("%d %d %d",&a,&b,&c);
if(a>b) //evaluates to true.
{
temp=a;
a=b;
b=temp;
}
else if(b>c) // not able to execute.
{
temp=b;
b=c;
c=temp;
}
else if(c>a) // not able to execute
{
temp=c;
c=a;
a=temp;
}
printf("%d %d %d",a,b,c);
return 0;
}
a = 8
b = 6
c = 3
checking a>b evaluates to true hence swapped
now:
a = 6 // your output
b = 8
c = 3
您可能需要再次探讨if else结构的概念
#include<stdio.h>
int main()
{
int a ,b,c;
printf("Enter the number : \n");
scanf("%d %d %d",&a,&b,&c);
if((a>b)&&(a>c))
{
if(b>c)
printf("%d %d %d",a,b,c);
else
printf("%d %d %d",a ,c,b);
}
else if((b>c)&&(b>a))
{
if(c>a)
printf("%d %d %d",b,c,a);
else
printf("%d %d %d",b,a,c);
}
else if((c>a)&&(c>b))
{
if(a>b)
printf("%d %d %d",c,a,b);
else
printf("%d %d %d",c,b,a);
}
return 0;
}
最简单的方法是使用数组而不是三个单独的变量。 然后使用qsort
对输入进行排序。
喜欢:
#include <stdio.h>
#include <stdlib.h>
// Compare function for qsort
int cmp(const void *p1, const void *p2)
{
if (*(int*)p1 < *(int*)p2) return -1;
if (*(int*)p2 < *(int*)p1) return 1;
return 0;
}
int main()
{
int arr[3];
if (scanf("%d %d %d", &arr[0], &arr[1], &arr[2]) != 3) exit(1);
// Sort the input
qsort(arr, sizeof(arr)/sizeof(int), sizeof(int), cmp);
printf("%d %d %d\n", arr[0], arr[1], arr[2]);
return 0;
}
#include <stdio.h>
int main()
{
int a,b,c,temp,min;
scanf("%d %d %d",&a,&b,&c);
if(a>b)
{
temp=a;
a=b;
b=temp;
}
if(c<a)
{
min=c;
c=b;
b=a;
a=min;
}
else if(c>a && b<c) {
min=c;
c=b;
b=min;
}
printf("%d %d %d",a,b,c);
return 0;
}
您正在比较使用else if
,如果一个条件满足则不会执行另一个else
条件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.