Function call passing incorrect number (C++ 11) - c++

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.

Related

Why isn't my code running the whole program but not producing any errors?

I need to calculate the digits of a rational number that I get from the user.
The problem is that even though there is no errors in the code, the program running only part of the code. I'm working in Visual Studio.
int sumDigits(int a);
// main function
int main()
{
int ratioNum;
// Ask from the user to enter a rational number
cout << "Hello" << endl;
cout << "Please enter a rational number: ";
// Get the number from the user
cin >> ratioNum;
// Inform the user what is the sum of the digits
cout << "The sum of the digits are: " << sumDigits(ratioNum) << "." << endl;
return 0;
}
// Definition of function
int sumDigits(int a)
{
int digit = 0, sum = 0;
// As long as number is bigger than 0, continue
while (a > 0)
{
// Define a new verible - digit, as a number mudolo 10
digit = a % 10;
}
// kick out the units digit that we used
a / 10;
// Sum the digits of the number
sum = digit + a;
// Return sum to the main function
return sum;
}
You need a /= 10 instead of a / 10, and you need it inside the loop. Otherwise the loop will run forever because a never gets modified inside of it, so it can never become 0.
This will fix the infinite looping issue but the result will still not be correct. Why that is would be a different question though, and I'd invite you to learn proper debugging first (google how to debug C)! This will help you a lot more than copying a solution from here.
Your code isn't running the whole program because of these lines:
while (a > 0)
{
// Define a new verible - digit, as a number mudolo 10
digit = a % 10;
}
Inside the while loop, you're only assigning the value to the digit variable, but not changing the value of a, so the value of a always remains greater than 0. So your code gets stuck inside the while loop.
You should write
// kick out the units digit that we used
a /= 10;

C++ Loop - Finding smallest and second smallest value

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.

My bool function keeps returning true and im not sure why

Im doing an excercise sheet to get an understanding of functions and I am currently working on the following question.
Write function prototypes for each of the following:
A function HasValue that may be passed a reference to an array, the size of the array and a
search value. The function should return true if the search value exists in the array
In my code I have sent the contents of the array, the array size and the value to be searched in the array to the bool function.
In the function I compared the value to each element of the array using a for loop.
I then created a variable count in the function that will be incremented if the value matches any element in the array.
I then used an if else statment to return true if count is greater than 0 and false if count is equal to 0. The problem is however that the function is only returning true thus the output will always be "this number appears in the array"
Logically these steps seem correct to me but obviously there is a flaw somewhere that I cant see. I presume its just I do not have a decent understanding of Bool functions yet but if someone could explain where and why I'm going wrong it would be greatly appreciated in my learning process to understanding functions and c++.
#include <iostream>
#include <iomanip>
#include "stdafx.h"
using namespace std;
bool HasValue(int Array[], int size, int Value);
int main()
{
int value;
int Array[10]{ 3,5,6,8,9,1,2,14,12,43 };
cout << "enter value you wish to search for in array " << endl;
cin >> value;
HasValue(Array, 10 , value);
if (true)
cout << "This number appears in the array " << endl;
else
cout << "This number does not appear in the array " << endl;
return 0;
}
bool HasValue(int Array[], int size, int Value)
{
int count = 0;
for (int i = 0; i < size; i++)
{
if (Value == Array[i])
{
count++;
}
}
if (count > 0)
{
return true;
}
else
return false;
}
You test code is the problem
HasValue(Array, 10 , value);
if (true)
cout << "This number appears in the array " << endl;
else
cout << "This number does not appear in the array " << endl;
This ignores the return value of HasValue and always prints "This number appears in the array".
HasValue(Array, 10 , value);
This line of code executes the function but ignores the returned value. When a function returns a value, you need to assign it to a variable:
bool result = HasValue(Array, 10 , value);
Then if (true) does not have any reference to the returned value. The true inside the if will cause the first cout to always print. You will never see the output from the else. But once you have the return value in a variable, you can use it in the if:
if(result)
You can reduce this all to one line of code, if you want:
if(HasValue(Array, 10 , value))
Now the if statement will directly test the return value from HasValue(). In this particular case, combining the code into a single line seems reasonable. You must be careful doing this, though. When you combine too much into a single line, the code becomes more difficult to debug. You will need to find a balance between readability and convenience as you continue learning how to program.

Working with vectors and loops

sorry to post a student question here. I'm not looking for a quick solution, I'm looking to understand. Comments in my code will explain the same, but here's a plain text version:
This is the beginning of a "LoShu Magic Square", I'm not to the addition of all parts of the matrix I'm making, I'm stuck at trying to verify that the same number has not been put into the rows before. My idea was to use one vector to "test" numbers that had been entered so far, so it does not need to be multi-dimensional (none of them are, but I don't care about the limit on the tester).
As-is the code will take the first number into the test vector, go to the check function, realize that number is there (which it should, haven't hashed out where to add the initial value), and after that initial check it will take ANY other value between 1-9, including repeats, which is bad. Help please? Why does it stop recognizing values inside the test vector after the initial round?
Separate link to code if it's maybe easier to read there: http://ideone.com/Dzh4mJ
#include<iostream> // This is the beginning of a "LoShu magic square" program for class, currently my
#include <vector> // goal is simply getting vectors to check whether or not a number has already been
using namespace std; // entered, and if so to go back and ask for another one. As-is it does not work
// through the first iteration. It recognizes the first number, says it's already in
bool theCheckening(vector<int>, int ); // and proceeds to take ANY numbers afterwards, repeats and all.
int main () {
int tester;
vector<int> loShu1; // Rows 1-3 of a "square"
vector<int> loShu2;
vector<int> loShu3;
vector<int> testCaseOut(1,0); // Test vector to iterate inside check function
do {
do{
cout << "Enter 1-9: "; // Working as intended, makes sure no number besides 1-9 is entered
cin >> tester;
} while (tester < 1 || tester > 9);
// Put initial value into test Vector
if (theCheckening(testCaseOut, tester)){ // If check function returns true, add value to row 1
loShu1.push_back(tester);
testCaseOut.push_back(tester);
cout << "It worked?!";
}
} while (loShu1.size() <= 2); // shooting for size of 3, working as intended
for (int var : loShu1) // Debug to see rows before maths and adding them (to come)
cout << var << " ";
cout << "\n";
for (int var : loShu2)
cout << var << " ";
cout << "\n";
for (int var : loShu3)
cout << var << " ";
return 0;
}
bool theCheckening(vector<int> testCaseInc, int testInt) {
int count;
vector<int> testCase(testCaseInc); // Initialize vector inside check function to current test numbers
for (int var : testCase)
cout << var << " ";
for (count = 0;count<=testCase.size();count++) { // for all the numbers inside the testing vector
if (testCase[count]!=testInt){ // if current position of test vector is ! in vector already,
cout << "ADDED!"; // add it to row back in main()
return true;
for (int var : testCase)
cout << var << " ";
}
cout << "ALREADY ENTERED!"; // Debug
cout << testCase.size();
return false; // otherwise, ignore and ask for another number
}
}
i think you have a logical error in your theCheckening function.
As far as i understand you want your function to return TRUE if the value is NOT in in the vector and FALSE if it IS in your vector.
Now to the problem:
Imagine someone has tipped in the following values to your code:
1 2 5 8
This values will be added to your vector and the vector will also contain:
1 2 5 8
Now let's say you tipp one more time the 2. Your Function will now start with value 1 of the vector and compare it to the 2. This is of course FALSE.
Look at your code:
if (testCase[count]!=testInt)
return true;
Your code says you can now return true. Which will cause your function to end and return true to the caller.
You didn't check the following values of the vector.
Your function theCheckening should look like this:
// user const vector<int> &, which will not cause to copy the
// vector
bool theCheckening(const vector<int> & testCase, int testInt) {
// use size_t which represents a integer datatype which
// is as big as arrays can be in the current bit setting
// 32 bit => size_t = unsigned int
// 64 bit => size_t = unsigned long long
for(size_t count = 0; count <= testCase.size(); count++) {
if(testCase[i] == testInt)
return false;
}
return true;
}
I hope this works and i understood this qestion correctly.

Code is not adding last defualt value

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.