Division Function w/ Multiple Return Possibilities - c++

I'm working on a school assignment, but I'm having trouble with a problem.
The problem is as follows:
"Write a function called divideIt that takes two integers, divides them, and returns the result as a float. Have this function skip division when it encounters an unacceptable value, and also retain the decimals. Do you know what to quit on?"
With the code I currently have, it divides and retains the decimal like the problem states, but I don't understand how to skip division. If I skip division because of an unacceptable value, what do I place in return? Should I just use null? Also, I'm not sure about the "Do you know what to quit on?" line.
My Code:
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
//Prototype
float divideIt(int num1, int num2);
int main()
{
int num1, num2;
float finalResult;
finalResult = divideIt(num1, num2);
cout << "Result: " << finalResult << endl;
}
//Header
float divideIt(int num1, int num2)
{
cout << "Simple Division\n" << "Input first integer: ";
cin >> num1;
cout << "Input second integer: ";
cin >> num2;
if(num2 == 0) //I wanted to make ASCII values unacceptable, but because they automatically translated into zeros, so I used that to my advantage on num2.
{
cout << "The second value was undefined or unacceptable." << endl;
}
return static_cast<float>(num1) / num2;
}

If I skip division because of an unacceptable value, what do I place in return?
You could return std::nanf ('not a number'):
if (num2 == 0)
return std::nanf ("");
There is also a corresponding std::isnan function.
Also, I'm not sure about the "Do you know what to quit on?" line.
Presumably, they mean 'what do you test for to decide that a value is unacceptable`. And I think we just did that.

Related

What is the difference between "sum = addTwoNumbers" to just calling "addTwoNumbers"?

I'm a freshman in IT and we're currently discussing functions in C++. I just want to ask the difference between our prof's code and the other code that I tried.
This is the sample code our prof showed us:
#include<iostream> //header file
using namespace std;
int num1, num2, sum = 0; // global variable
int addTwoNumbers(int a, int b)
{
sum = a + b;
return sum;
}
int main()
{
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
sum = addTwoNumbers(num1, num2);
cout << "\nThe sum is " << sum;
}
and as for the code I tried, I simply removed the "sum =" part. So,
addTwoNumbers (num1, num2);
cout << "\nThe sum is " << sum;
and it still did the same thing. At least, from what I saw in the output. Is there any difference between the two behind the scenes or is there really nothing?
The 1st code is ... confusing. I hope your professor didn't show this code to introduce you to functions, but to rather quiz your already knowledge of functions and global variables.
The confusing part are the global variables and how they are used inside the function. If we remove them and forget about them completely the code is better suited to teach you about functions. Let's see:
#include <iostream>
int addTwoNumbers(int a, int b)
{
int sum = a + b;
return sum;
// or simply:
// return a + b;
}
int main()
{
int num1, num2;
std::cout << "Enter first number: ";
std::cin >> num1;
std::cout << "Enter second number: ";
std::cin >> num2;
int sum = addTwoNumbers(num1, num2);
std::cout << "\nThe sum is " << sum;
}
Now there are no hidden dependencies between main and addTwoNumbers (in the form of the global variables). This illustrates the procedure of passing data to function and getting data back from the function (parameters and return). Analyze this code and understand how it works. Play with it.
Now this won't work:
addTwoNumbers (num1, num2);
cout << "\nThe sum is " << sum;
Because the only way data escapes the function is via its return. Since you discard the return value (you don't assign the result of calling the function) you don't have the result of the sum.
Now you could say you could do this instead:
int sum = num1 + num2;
cout << "\nThe sum is " << sum;
and ask "what's the point of functions?"
True for this particular small function there is no practical point of having it. You'll always write the num1 + num2 instead. However its simplicity makes it perfect as a teaching tool. You will soon see functions that get more complex and you will learn (either by being told or learning yourself the hard way) that writing code in very small chinks (functions) is better for both writing (breaking down the big problem in smaller problems) as well as for reading.
First of all, the reason why the sum is returning those values is that you are assigning the sum to itself. Basically, the addTwoNumber() returns the sum, and then you are assigning that value back into the sum. Hence, you don't need to assign the sum again in other words (sum = addTwoNumbers is unnecessary).
Yes, your code is working and it is actually better than the teachers in this case. However, your teacher may want to show you that you can use global variables like this. Typically you would store that value in another variable for later use if needed.

Homework Beginner C++: Unable to perform Type Casting during addition of integers

In order to help us understand type casting in C++, we are required to perform addition of two int's as shown below. If we provide two int's as 4 and 5 respectively, the output should be 4 + 5 = 9.
I tried to follow this type casting tutorial without any success. Could someone please provide me a hint or something?
Quoting the assignment verbatim.
Your friend wrote a program called an adder. The adder is supposed to take two numbers inputted by a user and then find the sum of those numbers, but it’s behaving oddly.
Your first task is to figure out what is wrong with the adder. Your second task is to fix it.
Hint(s) to identify the problem
Try entering 1 and 1. You expect the output to be 2 but you get 11 instead. Similarly, if you enter 3 and 4, you expect the output to be 7 but you get 34. Remember, string concatenation also uses the + operator.
Hint(s) to identify the solution
The + operator functions differently based on the type of data that comes before and after it. What data types will cause the + operator to calculate a mathematical sum? What data type is present in the program now? How do you convert from one data type to another? Check out the Type Casting page for some idea
#include <iostream>
using namespace std;
int main() {
string num1;
string num2;
cout << "Type the first whole number and then press Enter or Return: ";
cin >> num1;
cout << "Type the second whole number and then press Enter or Return: ";
cin >> num2;
string sum = num1 + num2;
cout << ( num1 + " + " + num2 + " = " + sum ) << endl;
return 0;
}
The problem with the code is that it is performing string concatenation when it needs to perform arithmetic addition instead. So you need to get the user's input into numeric variables, not strings. The assignment even alludes to this.
However:
Check out the Type Casting page for some idea
That is bad advice for this task, as you can't solve the problem with type casting.
You need to either:
Change the code to use int variables instead of string variables. This is the preferred solution, eg:
#include <iostream>
using namespace std;
int main() {
int num1;
int num2;
cout << "Type the first whole number and then press Enter or Return: ";
cin >> num1;
cout << "Type the second whole number and then press Enter or Return: ";
cin >> num2;
int sum = num1 + num2;
cout << num1 << " + " << num2 << " = " << sum << endl;
return 0;
}
Otherwise, if you want to continue using string variables, you need to convert (not type cast!) their values into int values at runtime, and then convert back afterwards, eg:
#include <iostream>
#include <string>
using namespace std;
int main() {
string num1;
string num2;
cout << "Type the first whole number and then press Enter or Return: ";
cin >> num1;
cout << "Type the second whole number and then press Enter or Return: ";
cin >> num2;
int sum = stoi(num1) + stoi(num2);
cout << ( num1 + " + " + num2 + " = " + to_string(sum) ) << endl;
return 0;
}
if you typecast a character or string it get's converted into its equivalent ASCII value , either you need to use stoi or subtract from '0' for every digit position(a bit repeatitive work) go with stoi

Cin appears to be failing inside this loop. Can anyone explain what I'm doing wrong?

I'm getting a compiler error when trying to build the code below and I don't quite understand what is failing and why.
It's pointing to line 45 (cin>>x[ctr]) with a "no type named 'type' in 'struct std::enable_if<false, std::basic_istream&>'" message.
I've just started coding a few days ago and English is not my native language. Apologies if this question is below the community's paygrade. Hope you can point me in the right direction.
cpp.sh/34sm3
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <iomanip>
//#include "_pause.h"
using namespace std;
//////////////////////////////////////////////////////////////////
// NOTE
// This is your program entry point. Your main logic is placed
// inside this function. You may add your functions before this
// "main()", or after this "main()" provided you added reference
// before this "main()" function.
//////////////////////////////////////////////////////////////////
//Write a program that can divide six non-zero integers (two integers per division) from the user and display the result to the user.
//Create a function that will perform the division operation. Display only the non-decimal part of the quotient.
float quot (int num1, int num2)
{
return num1/num2;
}
int main()
{
// ************************** TO DO **************************
// Place your code logic after this comment line
// ***********************************************************
int x[6];
cout<<"Enter 6 integers to divide: ";
for(int ctr=0; ctr<6; ctr++)
{
cin>>[ctr];
if(x[ctr]==0)
{
cout<<"Invalid number! Please enter a non-zero value: ";
cin>>x[ctr];
}
}
cout<<"The quotient of the first pair is: " << quot(x[0],x[1]) <<endl;
cout<<"The quotient of the second pair is: " << quot(x[2],x[3]) <<endl;
cout<<"The quotient of the third pair is: " << quot(x[4],x[5]) <<endl;
system ("pause");
return EXIT_SUCCESS;
}
Are cin statements inside for loops not allowed in C++?
i guess you need to replace cin>>[ctr] with cin>>x[ctr].....this might fix your error.
For starters the function quot should be written like
float quot (int num1, int num2)
{
return static_cast<float>( num1 ) / num2;
}
Otherwise the return type float does not make a great sense because in this expression num1 / num2 there is used the integer arithmetic.
It is obvious that in this statement
cin>>[ctr];
there is a typo. You forgot to specify the array name x
cin >> x[ctr];
Also it will be better to subsritute this if statement
if(x[ctr]==0)
{
cout<<"Invalid number! Please enter a non-zero value: ";
cin>>x[ctr];
}
for a while statement like
while ( x[ctr] == 0 )
{
cout<<"Invalid number! Please enter a non-zero value: ";
cin>>x[ctr];
}
That's all you had to do.
Just change cin>>[ctr] to cin>>x[ctr]
It's on line 41. You need to specify the array name, x before the index [ctr]
Here's your code.
I recommend you to use a debugger to figure out such small human-made-errors yourself.
Also, read your code and try to visualize its flow before asking for solutions.
int main()
{
// ************************** TO DO **************************
// Place your code logic after this comment line
// ***********************************************************
int x[6];
cout<<"Enter 6 integers to divide: ";
for(int ctr=0; ctr<6; ctr++)
{
cin>>x[ctr];
if(x[ctr]==0)
{
cout<<"Invalid number! Please enter a non-zero value: ";
cin>>x[ctr];
}
}
cout<<"The quotient of the first pair is: " << quot(x[0],x[1]) <<endl;
cout<<"The quotient of the second pair is: " << quot(x[2],x[3]) <<endl;
cout<<"The quotient of the third pair is: " << quot(x[4],x[5]) <<endl;
system ("pause");
return EXIT_SUCCESS;
}

One of my variables in my simple calculator says that it is not being initialized. Why?

I am a noob to C++, and as a part of homework I had to create a simple calculator with four functions within C++. I have done this and it works, however, I am now trying to loop it so that a user can have infinite attempts at using it, however, I am having struggles. Basically, when I run my program and tell the program which operation I'd like to use, it tells me that my variable "sum" is not being initialized. Im not quite sure what this is, or how to fix it. Any ideas? Here is my code -
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
while (true)
{
int num1, num2, r;
double sum;
cout << "Enter a number\n";
cin >> num1;
cout << "Enter another number\n";
cin >> num2;
cout << "Please enter an operator (+ , * , /, - or End)\n";
cin >> r;
if (r == 'End') break;
if (r == '+') sum = num1 + num2;
if (r == '-') sum = num1 - num2;
if (r == '*') sum = num1 * num2;
if (r == '/') sum = num1 / num2;
cout << r;
cout << "The answer is \n" << sum << endl;
system("pause");
return 0;
}
}
If the user enters 'a' as operator for example (something else than the valid choices), sum is never assigned a value, but sum is printed.
As others have said, the variable sum remains uninitialized if the user enters an invalid choice for r. Just set double sum=0; and you're good to go.
In addition, 'End' is not a char, so you can't compare it to r. You'll have to use some other option for ending.
The compiler says that you are trying to use an unintialized variable, sum.
If you think you initialize it, think again: You only assign a value if r is +, -, * or /. But what if r is a? 'End' is not a character, and thus invalid
Then sum is never initialized/has a value, and so the compiler complains.

Why does this cause in infinite loop with chars but not doubles?

I feel like im doing something really silly wrong. I just want the program to tell the user when they are entering non-doubles, and continue to loop back to the cin where you enter a value.
I want the user to input any number. Then essential do this trivial math and repeat. Its working fine in that regard, the problem comes when some unexpected input like a char gets entered. Then the input somehow sends it into a loop where it loops the math problem, instead of just telling the user that they must type a number and looping back to cin type in a new number.
#include <iostream>
#include <cstdlib>
using std::cout; using std::cin; using std::endl;
long double domath(long double i)
{
cout << i << "/" << 2 << "=" << i/2 << endl;
cout << i/2 << "*" << 10 << "=" << (i/2)*10 << endl << endl;
cout << 5 << "*" << i << "=" << 5*i << "\n\n";
return 0;
}
int main()
{
long double in = 0;
while(true)
{
cin >> in;
if (cin.fail()) {
in = char(int(in));
}
domath(in);
}
system("pause>nul");
return 0;
}
You don't clear the cin in case of fail, and it infinitely tries to parse wrong input to double, failing every time. You need to clear the buffer in case of error:
if (cin.fail()) {
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
in = char(int(in));
}
Also, can't understand what you're trying to achieve with
in = char(int(in));
in is a long double variable and will hold the last value you assigned to it, no need to "convert" it to do math.
Couldn't you try doing something like this?
int x;
if(std::cin >> x)
doSomethingCool(x);
else
std::cout << "Error, not a valid integer!" << std::endl;
Exit your loop on bad input.
I think this just feels more natural/looks cleaner than clearing the buffer and all the other jazz. Just my opinion.
if (cin >> x) - Why can you use that condition?
edit: Bul's answer is still a good one though.