Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ if/else if statement not working

I'm fairly new to C++ and I have to make a C++ program that sorts 3 numbers (smallest-greatest) using pass by reference. Everything works fine up until my if statement in my function. I have tried to do a lot of debugging and it seems like whenever I use "<" the statement doesn't execute. If I do (n1 > n2) the statement executes no matter what. If anyone can help that would be great. Here is my code:

#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;
}
like image 313
user2104913 Avatar asked Sep 01 '26 00:09

user2104913


1 Answers

You are using the wrong format specifier for scanf(). Instead of %d (signifying a pointer to an integer), use %lf (Pointer to a double). Alternately, change double to int in your code.

Note that your printf() statements suffer from a similar problem, and should be using either %f, %g or %e.

like image 67
Hasturkun Avatar answered Sep 03 '26 13:09

Hasturkun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!