I'm very very new to C++. Here I'm trying to write a program without any extra library. Using loops to find both the smallest value and the second smallest value from the user's inputs ( 0 is excluded and exits the program ).
Here is what I tried to do.
#include <iostream>
using namespace std;
int main()
{
int value=0;
int SmallestNumber=0;
int SmallestNumber2=0;
cout << "Enter number to find the smallest and second smallest(or 0 to exit): ";
cin >> value;
while (value != 0) {
if (value< SmallestNumber && value != 0 )
{
SmallestNumber = value;
}
else if (value<SmallestNumber && SmallestNumber2 >SmallestNumber && value != 0)
{
SmallestNumber2 = value;
}
cout << "Enter number to find the smallest and second smallest(or 0 to quit): ";
cin >> value;
}
cout << "Smallest number is: " << SmallestNumber << '\n' << endl;
cout << "Second Smallest number is: " << SmallestNumber2 << '\n' << endl;
return 0;
}
However, this program is not functioning properly. The smallest number finder works only if I input a negative value **, and the second smallest number value always outputs **0.
Since I'm very new to C++, I tried many other solutions, but this is what I can really think of.
Can somebody please tell me what is wrong with the program, and how I can correct it?
A million thanks! Please help me :'(
Thanks for answering my question!
I changed the initialization into this.
int value;
int SmallestNumber=0;
int SmallestNumber2=0;
but how do I initialize the smallest and the second smallest values..?
This is what I wanted my program to do
displaying the smallest and second smallest
50
1
61
93
-35
38
0
-35 smallest
1 second smallest
You start with a smallest value set to 0, so you will always get values only smaller than 0, that's why you have std::numeric_limits<int>::max().
Then for your second smallest, you are never checking against the current second smallest value, you are just checking against the biggest, which you now is going to work. So change this:
if (value>SmallestNumber2 && value != 0)
You should probably check value != 0 outside the main if statements as well. And as #Caleb reminded me, what happens to the previous largest value if it gets replaced?
Also, if you want to keep the same concept and do the algorithm "yourself" there is few things to change.
First the initial value of SmallestNumber and SmallestNumber2 need to be as high as possible otherwise the numbers saved can only be the one lower than your initial value. Therefore you can use INT_MAX.
Second, the second smallest number, need to be set in 2 cases :
when a new value is entered that is the second smallest
when a new smallest value is set, the old smallest value become the new second smallest.
Third there are a lot of unnecessary code here. You check too many time if value is not null which you know from the while condition. And you have code duplication with the cout/cin statement. Which is prone to mistakes.
Here is a version of what it could look like :
int value= INT_MAX;
int SmallestNumber=INT_MAX;
int SmallestNumber2=INT_MAX;
while (value != 0) {
if(value > SmallestNumber && value < SmallestNumber2)
{
SmallestNumber2 = value;
}
else if (value< SmallestNumber)
{
SmallestNumber2 = SmallestNumber;
SmallestNumber = value;
}
cout << "Enter number to find the smallest and second smallest(or 0 to quit): ";
cin >> value;
}
cout << "Smallest number is: " << SmallestNumber << '\n' << endl;
cout << "Second Smallest number is: " << SmallestNumber2 << '\n' << endl;
return 0;
ps : the version of #darune is a nicer solution.
You have no position at which the former smallest value becomes the second smallest value, which can't work.
Consider this code:
int value;
int smallest = std::numeric_limits<int>::max()-1;
int second_smallest = std::numeric_limits<int>::max();
while(true)
{
cin >> value;
if(value == 0) break;
if(value >= second_smallest) continue;
if(value == smallest) continue; // assuming that a double value does not change anything
if(value > smallest) // is between them
{
second_smallest = value;
continue;
}
//now the case left is that the new value is the smallest
second_smallest = smallest;
smallest = value;
}
Basic idea: first of all, rule out things and from then on, assume that they do not hold. We begin with the break case (I prefer a while(true) in such cases to have manual control over breaking it inside). Then we rule out the case in which nothing happens. The two cases left are that we are between the old values and that we are below both, and we handle them accordingly.
In your code, your ifs get to bloated. Makes it hard to keep track of what is done and what is to be done.
One example of this is that you have several times && value != 0 in your code despite this always being true due to the condition of your while.
In general, you should really learn how to use a debugger, or at least how to use helpful messages for debugging. Your mistake of setting your variables to zero at the start would have been easy to detect.
Other minor things: You should decide for a style and stick to it. It is quite unusual to name variables with a major first letter. Camel case is fine though, smallestNumber would have been fine. Second, try to avoid using namespace std;. This can lead to collissions. Rather use single members of std, like using std::cout;. It is not that problematic in a source file (very problematic in a header) but I recommend to do it consistently to keep a good routine.
A thing left to do in the code would be to later catch if the variables are still at std::numeric_limits<int>::max() and that minus one, signalling that there was no user input, and printing a fitting message instead of those values.
Note that as you read in an integer, negative values are legal, which might not be what you want, given that you use zero to break. You might want to add a case
if(value < 0)
{
cout << "Value was ignored due to being negative" << endl;
}
This is relatively simpel by using a a few different concepts, namely stdvector, stdstream and last stdsort
First off, the input part can be simplified to:
std::vector<int> numbers;
std::cout << "Enter multiple numbers, separated by spaces: ";
std::getline(std::cin, line);
std::istringstream stream(line);
while (stream >> number) {
numbers.push_back(number);
}
Now, since you would like the 2 smallest numbers, my suggested method would be to simply sort the vector at this point:
std::sort(numbers.begin(), numbers.end());
Now the list of numbers are sorted in ascending order and it is matter of printing the 2 first values. I leave that as an exercise to you.
Related
I am very new to c++ and I was trying to put together a script that just says how much older/younger someone is than me. The problem is the std::cin isn't working, it's not letting me say the input age. How do I make this work?
#include <iostream>
int main()
{
int age;
int diff = age - 20;
std::cout << "What is your age?\n";
std::cin >> age;
/* There should be an option to say the age, but it goes right into the next code with a random number */
if (diff < 20) {
std::cout << "You are " << diff << " years younger than me.\n";
}
else if (diff > 20) {
std::cout << "You are " << diff << " years older than me.\n";
}
else if (diff = 20) {
std::cout << "You are my age.\n";
}
}
When you say int age;, there's no rhyme or reason to the bits stored in memory that represent that integer. It's undefined behavior, but it will be equal to some random value based on what bits happen to be there. You then use std::cin to store an integer there, which works fine (assuming your code keeps chugging along despite using age before it has a value). Your conditionals then compare diff, which has a random value minus 20, with 20, outputting the right statement based on whatever was stored in diff. For example, when I ran your code, I got the output, "You are -1635346580 years younger than me." To fix this problem, read the value of the user's age before using it like this:
int age;
std::cout << "What is your age?\n";
std::cin >> age;
int diff = age - 20;
Additionally, when you wrote else if (diff = 20), you used an assignment operator. That puts the value of 20 into the variable diff. It then returns that value for use in the expected Boolean. In C++, 0 translates to false, and everything else translates to true. That means, once it gets there, it will always execute since 20 becomes true. Your program will always function correctly, however, since by that point in the code, diff is guaranteed to be 20 since it's neither greater than 20 nor less than 20. You could say else if (diff == 20) to do the comparison, but I'd replace it with else // diff is 20 since you know the value by that point.
I'm working my way thought Bjarne Stroustrup Programming Principles and Practice (4.64 Drill #6) and for some reason I can't get "if" to be true.
I've initialized my variables to -1000.
I can't initialize to null.
I've tried just declaring them
I've tried changing the order of my variables.
The problems I've found on stack overflow my code is much different than theirs.
I've currently added a vector which I wasn't using prior.
double val1 = 0; // initialized
double smaller; // initialized
double larger = 0; // initialized
vector<double> compare; // empty vector of doubles
int main ()
{
cout << "Please input a value, us | to stop\n"; // put into
while (cin >> val1) // cin "get from"
{
compare.push_back(val1);
if (val1 < smaller)
{
smaller = val1; // assignment giving a variable a new value
cout << val1 << " is the smallest so far \n" ;
compare.push_back(smaller);
}
else if (val1 > larger)
{
larger = val1; // assignment giving a variable a new value
cout << val1 << " is the largest so far \n";
compare.push_back(larger);
}
else
{
cout << val1 << " error\n";
}
}
}
I can't get smaller "is the smallest so far to print.
I'm teaching myself so any input would be greatly appreciated if anything in my code isn't correct or the best practices please let me know.
Thank You in Advance,
The first value enter must be both the larger and the smaller whatever that value, for that you need to initialize smaller with INFINITY (all valid values are smaller) and larger with -INFINITY (all valid values are larger) and to remove the else to have the two clauses effective for the first value, the third clause has no sense and must be removed.
Is it also useless to use global variables, I encourage you to not use global variables the more you can.
Because the same value can be enter several time perhaps you want a set rather than a vector to not save several times the same value ? However you do not use compare after ...
You write the message Please input... only one time, in that case it is more consistent to say Please input values... or replace
cout << "Please input a value, us | to stop\n"; // put into
while (cin >> val1) // cin "get from"
{
by
while (cout << "Please input a value, invalid value or EOF to stop" << endl,
cin >> val) // cin "get from"
Your code can be changed to be :
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int main ()
{
double val;
double smaller = INFINITY; // initialized
double larger = -INFINITY; // initialized
vector<double> compare; // empty vector of doubles
cout << "Please input values, give an invalid value or EOF to stop" << endl; // put into
while (cin >> val) // cin "get from"
{
compare.push_back(val);
if (val < smaller)
{
smaller = val; // assignment giving a variable a new value
cout << val << " is the smallest so far" << endl;
compare.push_back(smaller);
}
if (val > larger)
{
larger = val; // assignment giving a variable a new value
cout << val << " is the largest so far" << endl;
compare.push_back(larger);
}
}
// do something with compare ?
return 0;
}
Execution :
pi#raspberrypi:/tmp $ ./a.out
Please input values, give an invalid value or EOF to stop
1234
1234 is the smallest so far
1234 is the largest so far
1
1 is the smallest so far
222
222222
222222 is the largest so far
-123
-123 is the smallest so far
23
45
aze
pi#raspberrypi:/tmp $
Initialise your variables to INFINITY.
double smaller = INFINITY;
double larger = -INFINITY;
The first value will be smaller/larger than any of those, so you don't limit their value range.
edit: As somebody in the comments pointed out, you would also have to remove the else between the smaller/larger parts, as for that first round, both would apply. As for the third case, not sure what that is meant to do.
I am writing a program to find a 4-digit address. The program should continually allow the user to enter digits until the correct answer is solved. Additional parameters are:
All four digits are different
The digit in the thousands place is three times the digit in the tens
place
The number is odd
The sum of the digits is 27
With the program I've written so far it gives me the same output of "address is correct" no matter the input is. Trying to figure out what I am doing wrong, but no success. This is the code I've written so far.
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main()
{
int const Address = 9837;
int input;
char Y;
char N;
int sum;
int even;
int i;
cout << "Please enter a 4-digit number." << endl;
cin >> input;
{
while (input = Y || N)
{
if (input = Y)
cout << "Please enter a 4-digit number" << endl;
else if (input = N)
cout << "Good Bye!!" << endl;
return 0;
}
while (input != Address && Y && N)
{
if (sum = input == !27);
cout << "Not a valid address - the sum of the digits is not 27" << endl;
if (input % 2 == 0)
cout << "Not a valid address - the number is even." << endl;
}
input = Address;
cout << "Address is correct." << endl;
}
}
You include <cmath> and <string> but you don't use anything from that headers.
Declare/define variables as close to where they're used/needed.
You are using the variables N and Y uninitialized. They contain an indeterminate value (=garbage). If char happens to be unsigned, reading an indeterminate value (an uninitialized (unsigned) char) under a few certain conditions is allowed. But you use N and Y in a way where reading their values causes undefined behaviour.
The variables even and i are never used.
With cin >> input; you try to extract an integer from standard input. If the user would enter Y or N or anything else that is not an integer, extraction would fail. You need two different ways to get the users input: 1 to let the user enter his guessed number and 1 to let the user choose if he wants to play again.
You introduce a block ({) after cin >> input; that serves no purpose.
while (input = Y || N) ... Comparison is done with the operator == in C++ (and C) but = is assignment. The expression input = Y || N assigns the result of Y || N to input but since Y and N are uninitialized and chances that both contain the value 0 is quite low (0 || 0 would evaluate to false), input will almost always be 1 (true converted to an int is 1) and the loop will always execute.
Actually, reading the values of Y and N causes undefined behaviour because they're uninitialized. Theoretically (since the compiler knows that Y and N have indeterminate value), it can generate any code it likes.
Within the first while-loop:
if (input = Y) // is again an assignment, not a test for equality
cout << "Please enter a 4-digit number" << endl;
else if (input = N) // again
cout << "Good Bye!!" << endl;
return 0; // will always exit the program, no matter the value of input
In case all hell breaks loose and N and Y are both 0 by chance and thus the 2nd while-loop is reached, it is sure, that input is 0 (because otherwise the controlled statement of the 1st while-loop would have been executed and exited the program by return 0;). When input equals 0 it isn't equal to Address so input != Address yields true but since we know that N and Y are 0 (false) and true && false gives false, the controlled statement of the 2nd while-loop doesn't get executed.
I'll skip the contents of the controlled statement of the 2nd while-loop. Sufficive to say, they don't do what you think they do.
input = Address; // that assignment serves no purpose
cout << "Address is correct." << endl;
is the output you always get when the variables Y and N are 0, which might happen (especially when running debug-code).
Please, stay away from the source you're currently learning C++ from. Get a good textbook and start over.
Is the piece of code you have captured here missing something or incomplete? I see that Y, N and sum are not assigned any value and thus all conditions checks fail... Eventually it will display "Address is correct" always...
Remember that = and == are totally different.
= means an assignment. eg: int x = 100; means put the value of 100 into the variable x.
== means comparison or (is equal to). eg: if (x == 100), means if x has the value 100.
Also, If you're trying to make a choice variable for Yes or No,
You should do it this way:
char ans;
if (ans == 'Y' || ans == 'N")
Since your input variable is an int, and your choice variable is a char, your while statement is not valid.
A few things you need to know:
You should assign values to things before calling them
You should read about the difference between = and ==
If you want multiple inputs, your cin >> input; should be in your while loop
Your code is not well indented at some places
You are declaring a i integer, but you are never using it.
In other words: your compiler must be giving you a LOT of warnings. Did you look at them?
I'm currently working on a project that is meant to teach the usage of functions in C++. I've worked with python in the path and have a reasonable understanding of functions in code (or so I thought) but for some reason I'm getting some alarming errors when I pass values through to my current function.
This is the entire code, my problem lies within the narc_num(153,3) call made in main. I added some cout statements into the narc_num function to see why I was getting wonky results and found that the num argument was getting passed as a completely different number. Why would this be?
#include<iostream>
#include<cmath>
using std::cin;
using std::cout;
using std::endl;
/*
Function: order_parameters
Purpose: If first is greater than second reassign the values so second is greater than first
Algorithm:
1.Pass arguments as references to first and second
2.if statement that runs if first is greater than second
3.within if statement switch values using a temporrary variable
4.if else doesnt run nothing happens
*/
void order_parameters(long & first,long & second)//passing long references of first and second
{
if(first > second)//start if when the ref to first > ref to second
{
long temp; // initialize temp
temp = second; //value temp is = to second
second = first; //second will now be first, temp is still = to first though as well
first = temp; //second is now set = to temp, which is first. dat swap
}//end if
}
/*
Function: narc_num
Purpose: check if a number is indeed a narcisstic number
Algorithm:
1.Pass num, the number to be checked, and power, the order the number will be checked against
2.use a while loop to iterate through digits of number
-mod10 takes the last digit, the digit is raised to the power passed as an argument
-the value found is added to the total
-the number is then divided by 10 to remove the last digit, reiterates again.
3.the total found by the while loop is checked against the number passed an as argument
-if the total is equal to the number it is narcisstic.
*/
bool narc_num(long num, long power)// will return a boolean value, passing num and power integers
{
//split all digits into seperate numbers, add together raised to power
long total = 0,digit,num_copy;
bool narc = false; //value to check if number is narcissitic or not
num = num_copy;
cout << "number"<< num << endl;
while(num > 0)
{digit = num%10;
cout <<"digit" << digit << endl;
total += pow(digit,power);
cout <<"total" << total << endl;
num /= 10; //divides by 10 to go to the next digit down
}
if (total == num)
narc = true;
cout << total << endl;
return narc;
}
long check_range(long first,long last,long power)
{
bool check;
order_parameters(first,last); //make sure parameters are in correct order
for(first;first == last;first++);//iterate through all numbers from first to last
{check = narc_num(first,power); //check = True if narc number otherwise false
if (check == true)
{cout << first <<" is a narcissistic number of order " <<power<< endl;
};
cout << "gothere"<< endl;
};
cout << "dick canoe"<< endl;
}
int main(){
narc_num(153,3);
}
You are assigning the value of num_copy (an uninitialized long) to num near the top of the narc_num function. I believe you meant to assign num_copy the value of num. This is probably the cause of your unexpected results.
Im writing an application for my intro to programming class and the objective is to
set up a simple program that prompts the user to enter a series of positive integer numbers between 50 and 100 (inclusive) using the keyboard. Your prompt should tell the user to enter a negative number to stop the input process.
As the user enters the numbers, you should keep track of the number of valid entries they have made (those that fall in the allowed range), and add up those numbers entries. You do not need to store more than the single entered number, the count, and the current total you are calculating.
Once the user completes the data entry, produce output similar to this:
A total of 5 values were entered.
The sum of those numbers is 127
make a program that will have one variable and it will retrieve the users
Here is the code I wrote
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
int loop = 1;
int value;
int times = 0;
cout << "Enter a negavtive number to quit" << endl;
cout << "\nPlease Enter Any Number Between 50 - 100" << endl;
while (loop == 1) {
cin >> value;
times++;
value += value;
if(value < 0) {
cout << "You entered " << times - 1 << " numbers" << endl;
cout << "Total: " << value << endl;
system("PUASE");
return EXIT_SUCCESS;
}// end if statement
} //end while loop
system("PAUSE");
return EXIT_SUCCESS;
}
Here is the output
http://www.flickr.com/photos/62751645#N08/6286454476/
I think it may have something to do with the fact that I am using the int value to do two different tasks.
How might I go about fixing this?
revision
thanks to all of you for the "fix"
I add a new variable and it works like a charm, but now the math is not adding correctly
http://www.flickr.com/photos/62751645#N08/6286526294/in/photostream
There are a few problems, but the major one is this:
cin >> value;
This means "overwrite value with the number the user inputs", and of course if you do that you will never be able to store a sum inside value because it will be overwritten each time with the new number.
Solution: use another variable to keep the running total.
You also have a bug in that you do
times++;
value += value; // which as described above will not "stick"
before checking if value is negative. These operations should only be performed when value is not negative; otherwise, data entry should stop immediately and the negative number should not be taken into account for summing the total.
add a sum variable to hold the sum, you overwrite the input value in every loop iteration.
sum += value;
Don't use value to do two different tasks.
Have another variable called sum and accumulate the total there.
The way you're doing things you are writing over your sum every time the user enters a number:
cin >> value; // sum of previous values is overwritten!
Also there's another problem in that when the user enters a negative number you add that to the sum as well.
Your code does not check whether the values are in range (i.e. between 50 and 100). You can put a condition on the line where you do the addition as below:
if (value >= 50 && value <= 100)
sun += value;
Also, you can use 'value' to break the loop also.