2013-02-24 175 views
3

我對C++相當陌生,而且必須使用傳遞引用來製作一個C++程序,它可以對3個數字(最小最大)進行排序。一切工作正常,直到我的函數if語句。我試圖做很多調試,並且似乎每當我使用「<」時,語句都不執行。如果我做(n1 > n2)該聲明執行無論如何。如果任何人都可以提供幫助,那會很棒。這裏是我的代碼:C++ if/else if語句不起作用

#include <cstdlib> 
#include <iostream> 
#include <stdio.h> 

using namespace std; 

int sortNum(double &n1, double &n2, double &n3); 

int main(int argc, char *argv[]) { 
    double num1, num2, num3; 

    printf("Welcome to Taylor's Sorting Program \n"); 
    printf("Enter 3 numbers and the program will sort them \n"); 
    printf("Number 1: \n"); 
    scanf("%d", &num1); 
    printf("Number 2: \n"); 
    scanf("%d", &num2); 
    printf("Number 3: \n"); 
    scanf("%d", &num3); 

    sortNum(num1, num2, num3); 

    printf("Sorted Values \n"); 
    printf("Number 1: %d ", num1); 
    printf("\t Number 2: %d ", num2); 
    printf("\t Number 3: %d \n", num3); 

    system("PAUSE"); 
    return EXIT_SUCCESS; 
} 

int sortNum(double &num1, double &num2, double &num3) { 
    double n1, n2, n3; 
    n1 = num1; 
    n2 = num2; 
    n3 = num3; 


    if (n1 < n2 && n1 > n3) { 
     num1 = n2; 
     num2 = n1; 
     num3 = n3; 
    } else if (n2 < n1 && n2 > n3) { 
     num1 = n3; 
     num2 = n2; 
     num3 = n1; 
    } else if (n3 < n2 && n3 > n1) { 
     num1 = n2; 
     num2 = n3; 
     num3 = n1; 
    } 
    return 0; 
} 
+0

您需要查看「scanf」 - 「scanf(」%ld「,&numX)」的手冊。 – 2013-02-24 17:06:57

+1

有6種方法可以重新排列3個數字,而您的功能只有3種可能的結果。 – interjay 2013-02-24 17:08:17

+0

scanf和printf不是C++。它們是繼承的C-isms,它們不是類型安全的。我建議你不要使用它們。 – 2013-02-24 18:18:43

回答

5

您正在使用錯誤的格式說明符scanf()。 而不是%d(表示指向整數的指針),請使用%lf(指向double的指針)。 或者,在您的代碼中將double更改爲int

請注意,您的printf()聲明遭受類似問題,應使用%f,%g%e

1

有三個不同數字的6個可能的順序(排列)。

你的代碼出現,檢查只有3個,分別是爲了,

    N3 < N1 < N2

    N3 < N2 < N1

and

    N1 < N3 < N2

在3其他情況下你只return 0,僅此而已。

從我上面的系統清單中,你能猜出另外三個案例的共同之處,它們是如何相似的?


順便說一句,不問,但你會從噸的麻煩,通過使用C++ cincout,而不是低級別的C函數scanfprintf保存自己。

+0

謝謝你的幫助。 – user2104913 2013-02-24 17:31:23