Write a C++ program that inputs a wavelength and then displays the associated light color. If the wavelength is shorter than 400 nm or longer than 700 nm, display the message “Wavelength outside visual range”. Classify boundary wavelengths as the lower-wavelength color. For example, label a wavelength of 424 nm as violet.

#include <iostream>
using namespace std;
int main()
{
int num;

cout<< “Please enter a wavelength range: “;
cin>>num;

if (num = 400 && num <=424)
         cout<< “ Violet “;
else if (num = 425 && num <= 491)
        cout<< “ Blue “;
else if (num = 492 && num <= 575)
        cout<< “ Green “;
else if (num = 576 && num <= 585)
       cout<< “ Yellow “;
else if (num = 586 && num <= 647)
       cout<< “ Orange “;
else if ( num = 648 && num <= 700)
       cout<< “ Red “;
else (num < 400 || num > 700)
cout<< “ Wavelength outside visual range “;
return 0;
}

This is my code it is working but when ever I enter a number it always give me "Blue"

You are using the wrong operator in your if statements. You need to be using the == operator in your if statements, not the = operator!

= is the assignment operator, used to assign a value to a variable.
Whereas == is the test for equality.

EDIT:
In fact, the == operator is incorrect. After looking at your code again, you need to be using the >= (greater than or equal to) operator:
e.g.

if (num >= 400 && num <=424)
    cout<< “ Violet “;
else if (num >= 425 && num <= 491)
    cout<< “ Blue “;
else if (num >= 492 && num <= 575)
    cout<< “ Green “;
else if (num >= 576 && num <= 585)
    cout<< “ Yellow “;
else if (num >= 586 && num <= 647)
    cout<< “ Orange “;
else if ( num >= 648 && num <= 700)
    cout<< “ Red “;
else
    cout<< “ Wavelength outside visual range “;

Edited 2 Years Ago by JasonHippy

This question has already been answered. Start a new discussion instead.