【问题标题】:C programming, if statements (large to small integer swap)C 编程,if 语句(大到小整数交换)
【发布时间】:2016-02-06 00:28:59
【问题描述】:

我一直在努力获取将 3 个数字按升序然后降序排列的代码。但是,代码会跳过 if 语句并假定数字是按顺序排列的。这是我第一次在 C 中使用 if 语句,也是我第二天的学习指南,因此我们将不胜感激。谢谢

#include<stdio.h>
void swap(int *, int *, int *);
int main(void){

printf("Please enter the first number to sort: ");
scanf("%d",&numberOne);

printf("Please enter the second number to sort: ");
scanf("%d",&numberTwo);

printf("Please enter the third number to sort: ");
scanf("%d",&numberThree);

//swap

swap(&numberOne, &numberTwo, &numberThree);

//return results

printf("The three numbers in descending order is: %d, %d, %d", 
numberOne, numberTwo, numberThree);

printf("THe three numbers in ascending order is: %d, %d, %d", 
numberThree, numberTwo, numberOne);
}

void swap(int *numberOne, int *numberTwo, int *numberThree){
if (numberOne>numberTwo){
if (numberTwo<numberThree){
int temp =*numberTwo;
*numberTwo=*numberThree;
*numberThree = temp; }
// "312"

else if (numberTwo>numberOne){
    if (numberOne>numberThree){
    int temp =*numberOne;
    *numberOne =*numberTwo;
    *numberTwo= temp;
    // "231"
}
    else if(numberOne<numberThree){
    if(numberTwo>numberThree){
    int temp =*numberOne;
    *numberOne =*numberTwo;
    *numberTwo =*numberThree;
    *numberThree = temp;
    // "132"
    }
    }
}
else if (numberThree > numberOne){
    if (numberTwo< numberOne){
    int temp =*numberThree;
    *numberThree =*numberTwo;
    *numberTwo =*numberOne;
    *numberOne = temp;
    // "213"
}
else {
    int temp = *numberThree;
    *numberThree = *numberOne;
    *numberOne = temp;
    // "123"
    }
}

}
else{
printf("Look at that these numbers were in order...");
}
}

【问题讨论】:

  • 尝试提出聪明的问题。尝试找到一个最小的代码,它仍然显示你的问题。大多数时候,您会在这个过程中自己找到解决方案。
  • 我会建议:让代码更易于阅读,从而使代码更易于调试。适当缩进它会容易得多。模块化时也更容易调试;您需要一个交换 2 个整数的函数,因为您重复执行此操作。尝试这些方法,正如 michas 指出的那样,您也许可以自己修复它——从长远来看,成为一个编写清晰、可调试代码的人必须比解决一个特定问题更重要。

标签: c pointers if-statement integer


【解决方案1】:

当您这样做时:if (numberTwo&gt;numberOne),您正在比较指针。您需要比较这些指针后面包含的值。这样做:if (*numberTwo&gt;*numberOne)

【讨论】:

  • mk,我改变了它,它仍然给我同样的命令。我会继续调查的
【解决方案2】:

这行得通吗? !!! 顺便提一句! “大整数”和“小整数”的定义还有其他的技术含义。

void swap(int *numberOne, int *numberTwo, int *numberThree){
    int tmp;

    if(*numberOne > *numberThree ){
        tmp             = *numberThree;
        *numberThree    = *numberOne;
        *numberOne    = tmp;
    }


    if(*numberTwo > *numberThree ){
        tmp             = *numberThree;
        *numberThree    = *numberTwo;
        *numberTwo    = tmp;
    }
    if(*numberOne > *numberTwo ){
        tmp             = *numberTwo;
        *numberTwo    = *numberOne;
        *numberOne    = tmp;
    }


}

【讨论】:

    猜你喜欢
    • 2022-01-17
    • 2014-03-30
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    • 1970-01-01
    相关资源
    最近更新 更多