Double function returning as an integer - c++

I would like to know why does my double function returns as an integer instead of a decimal. I gave a value of 0.01 to my ic4 to go into the function and expect a return of 0.384615 but instead i get a return of 1.
#include <iostream>
#include <string>
#include <cmath>
#include <math.h>
using namespace std;
double vt = 0.026;
double ic4;
double gm7(double IC7);
int main ()
{
while(true)
{
printf("ao (in dB): ");
cin >> ao;
if (ao >= 80)
{
printf("IC7 (in Amps): ");
cin >> ic7;
cout << "IC7: " << ic7 << endl;
gm7(ic7);
cout <<"gm7: " << gm7 << endl;
}
else
{
printf("Choose another ao!\n");
}
}
}
double gm7 (double IC7)
{
return IC7 / vt;
}

gm7 is a function. You are inserting a function into the character stream.
Character streams do no have an insertion operator overloads for functions. However, they do have an overload for bool and function pointers implicitly convert to bool and function implicitly converts to a function pointer. Since the function pointer is not null, it converts to true. true is printed as 1.
P.S. The example program is ill-formed because it uses undeclared names.

just to clarify the comments
you should do this
int main ()
{
while(true)
{
printf("ao (in dB): ");
cin >> ao;
if (ao >= 80)
{
printf("IC7 (in Amps): ");
cin >> ic7;
cout << "IC7: " << ic7 << endl;
double gm7res = gm7(ic7); <======
cout <<"gm7: " << gm7res << endl; <<======
}
else
{
printf("Choose another ao!\n");
}
}
}
note you also need to declare a0

Related

Make console title bar display the value of a variable

I'm working on a small program that counts up to a number given by the user. The number they enter is stored in the variable limit. I want the number in that variable to be displayed in the title kind of like this: "Counting up to 3000" or "Limit set to 3000" or something like that. I've tried using SetConsoleTitle(limit); and other things but they just don't work. With the code that I have posted bellow, I get the following error:
argument of type "int" is incompatible with parameter of type "LPCWSTR"
I'm currently using Visual Studio 2015 if that's important in any way.
#include <iostream>
#include <windows.h>
#include <stdlib.h>
using namespace std;
int main()
{
begin:
int limit;
cout << "Enter a number you would like to count up to and press any key to start" << endl;
cin >> limit;
SetConsoleTitle(limit); // This is my problem
int x = 0;
while (x >= 0)
{
cout << x << endl;
x++;
if (x == limit)
{
cout << "Reached limit of " << limit << endl;
system("pause");
system("cls");
goto begin;
}
}
system("pause");
return 0;
}
The SetConsoleTitle() function expects a string as its argument, but you're giving it an integer. One possible solution would be to use std::to_wstring() to convert an integer to a wide-character string. C++ string that you get as a result has a different format from the null-terminated wide-character string that SetConsoleTitle() expects, so we need to make the necessary conversion using the c_str() method. So, instead of
SetConsoleTitle(limit);
you should have
SetConsoleTitle(to_wstring(limit).c_str());
Don't forget to #include <string> for to_wstring() to work.
If you want a title that includes more than just a number, you'll need to use a string stream (a wide character string stream in this case):
wstringstream titleStream;
titleStream << "Counting to " << limit << " goes here";
SetConsoleTitle(titleStream.str().c_str());
For string streams to work, #include <sstream>. Here's the full code:
#include <iostream>
#include <string>
#include <sstream>
#include <windows.h>
#include <stdlib.h>
using namespace std;
int main()
{
begin:
int limit;
cout << "Enter a number you would like to count up to and press any key to start" << endl;
cin >> limit;
wstringstream titleStream;
titleStream << "Counting to " << limit << " goes here";
SetConsoleTitle(titleStream.str().c_str());
int x = 0;
while (x >= 0)
{
cout << x << endl;
x++;
if (x == limit)
{
cout << "Reached limit of " << limit << endl;
system("pause");
system("cls");
goto begin;
}
}
system("pause");
return 0;
}

Function must return a value

I am trying to make a text based RPG and i'm fairly new to c++. I understand that I need to return a value, but when I try and return CharacterName or CharacterRace it comes up with unresolved externals errors. I'd really appreciate the help guys, thanks :)
CharacterCreation.h
#include <string>
#include <iostream>
void petc(), ConsoleClear(), petc(), EnterClear();
std::string CharacterName, CharacterRace;
Main.cpp
#include <iostream>
#include <limits>
#include <string>
#include <string.h>
#include "CharacterCreation.h"
std::string CharacterCreation();
int main()
{
CharacterCreation();
}
std::string CharacterCreation(int RaceChoice, int RaceChoiceLoop)
{
RaceChoiceLoop = 0;
std::cout << "Welcome to the character creation V 1.0.0" << std::endl;
EnterClear();
std::cout << "Choose a name: ";
std::cin >> CharacterName;
std::cout << CharacterName << std::endl;
EnterClear();
while (RaceChoiceLoop == 0)
{
std::cout << "(1) Human - Human's race perks: + 5 to Magic | + 1 to Sword Skill" << std::endl;
std::cout << "(2) Elf - Elve's race perks: + 5 to Archery | + 1 to Magic" << std::endl;
std::cout << "(3) Dwarf - Dwarven race perks: + 5 to Strength | + 1 to Archery" << std::endl;
std::cout << "Choose a race, " << CharacterName << ": ";
std::cin >> RaceChoice;
if (RaceChoice == 1)
{
RaceChoiceLoop = 1;
CharacterRace = "Human";
}
else if (RaceChoice == 2)
{
RaceChoiceLoop = 1;
CharacterRace = "Elf";
}
else if (RaceChoice == 3)
{
RaceChoiceLoop = 1;
CharacterRace = "Dwarf";
}
else
{
std::cout << "Invalid Option";
EnterClear();
RaceChoiceLoop = 0;
}
}
}
void petc()
{
std::cout << "Press Enter To Continue...";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
void EnterClear()
{
std::cout << "Press Enter To Continue...";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
system("cls");
}
void ConsoleClear()
{
system("cls");
}
A declared std::string function should return a string and this is not the same as printing it on the screen, use return "something" inside the function otherwise declare it void.
The "unresolved externals" message isn't directly caused by your returning a value.
It's a linker error, and only occurs because compilation succeeded.
The cause is that you're declaring, and calling, this parameter-less function:
std::string CharacterCreation();
but you're defining this function with two parameters:
std::string CharacterCreation(int RaceChoice, int RaceChoiceLoop)
The declaration and the definition must match.
From the looks of it, you don't actually want the parameters and should use local variables instead:
std::string CharacterCreation()
{
int RaceChoice = 0;
int RaceChoiceLoop = 0;
// ...
Problem is that the function CharacterCreation() (taking no arguments) is never defined, and thus the linker cannot find it.
Try substituting in the following:
std::string CharacterCreation(int, int);
int main()
{
CharacterCreation(1,1);
}
This will call the CharacterCreation function you have implemented below the main function. Doing this I can compile (and link) your code :)
As I have pointed in my comment before, your CharacterCreation method does not return any value, although you have defined a string as an expected one.
What you most likely want to do is either change CharacterCreation signature to:
void CharacterCreation(int RaceChoice, int RaceChoiceLoop)
and keep the current implementation
or pack all your console output in a string and return it at the end of the method.
Then in main()
string result = CharacterCreation();
can retrieve this value and you can print it in main

C++ Nonstatic member referencing must be relative to specific object

This Complex Number program is supposed to take three arguments from a txt document, the first to indicate whether the subsequent two are numbers in polar or rectangular form, and output every complex number given in both rectangular and polar form. Both the header file and source code are shown here. The txt document is in the following format:
p 50 1.2
r 4 0.8
r 2 3.1
p 46 2.9
p 3 5.6
Without declaring the int inputfile() function as static within the class declarations, the build gives an error 'illegal call of non-static member function'.
With the static declaration of the function (shown below), the build gives errors referring to the class members Pfirst, Psecond, Rfirst and Rsecond inside function definition inputfile(), being 'illegal references to non-static members'.
The member declarations cannot then be made static as well because the class would not be able to initialise the parameters within the constructor.
How can I bypass this 'static' problem?
#define Complex_h
class Complex
{
char indicator;
const double pi;
public:
double Pfirst, Psecond, Rfirst, Rsecond;
Complex(char i = 0, double Pf = 0, double Ps = 0, double Rf = 0, double Rs = 0, const double pi = 3.14159265) // with default arguments (= 0)
: indicator(i), Pfirst(Pf), Psecond(Ps), Rfirst(Rf), Rsecond(Rs), pi(pi) {}
~Complex();
void poltorect();
void recttopol();
static int inputfile();
};
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <string>
#include "Complex.h"
using namespace std;
int Complex::inputfile()
{
ifstream ComplexFile;
ComplexFile.open("PolarAndRectangular.txt");
string TextArray[3];
string TextLine;
stringstream streamline, streamfirst, streamsecond;
while (getline(ComplexFile,TextLine))
{
streamline << TextLine;
for (int j=0; j<3; j++)
{streamline >> TextArray[j];}
streamline.str("");
streamline.clear();
if (TextArray[0] == "r")
{
streamfirst << TextArray[1];
streamfirst >> Rfirst;
streamsecond << TextArray[2];
streamsecond >> Rsecond;
cout << "Complex number in rectangular form is " << Rfirst << "," << Rsecond << endl;
void recttopol();
cout << "Complex number in polar form is " << Pfirst << "," << Psecond << endl;
}
else
{
streamfirst << TextArray[1];
streamfirst >> Pfirst;
streamsecond << TextArray[2];
streamsecond >> Psecond;
cout << "Complex number in polar form is " << Pfirst << "," << Psecond << endl;
void poltorect();
cout << "Complex number in rectangular form is" << Rfirst << "," << Rsecond << endl;
}
streamfirst.str("");
streamfirst.clear();
streamsecond.str("");
streamsecond.clear();
}
ComplexFile.close();
system("pause");
return 0;
}
void Complex::recttopol()
{
Pfirst = sqrt((Rfirst*Rfirst)+(Rsecond*Rsecond));
Psecond = (atan(Rsecond/Rfirst))*(pi/180);
}
void Complex::poltorect()
{
Rfirst = Pfirst*(cos(Psecond));
Rsecond = Pfirst*(sin(Psecond));
}
int main()
{
Complex::inputfile();
system("pause");
return 0;
}
You forgot to create an object of type Complex.
Make your inputfile() method nonstatic and do:
int main()
{
Complex complex; // Object construction.
complex.inputfile();
system("pause");
return 0;
}

Error with uninitialized variables and returns

I'm having some problems with my program which I do not understand.
On line 72, I get the error: "error C4700: uninitialized local variable 'sumInEuros' used" however surely it is initialized as I am using it to store a calculation?
Also on line 66 I get "error C4716: 'showPriceInEuros': must return a value" - why must this return a value? the function is simply meant to output a message to the console.
I'm using VS13 and it's c++.
Any help would be very much appreciated, because I am stuck!
Thanks!
#include <iostream> //for cin >> and cout <<
#include <cassert> //for assert
#include <iomanip> //for endl
#include <Windows.h>
using namespace std;
void processAPrice();
int getPriceInPounds();
int convertPriceIntoEuros(int pounds);
int showPriceInEuros(int pounds, int euros);
int calculateSum(int euros);
void produceFinalData(int sum, int numberOfPrices);
int main()
{
char answer('Y');
int numberOfPrices(0);
while (answer = 'Y')
{
processAPrice();
numberOfPrices++;
cout << "Continue? (Y/N)";
cin >> answer;
}
if (numberOfPrices > 0)
//produceFinalData(sum, numberOfPrices);
system("PAUSE"); //hold the screen until a key is pressed
return(0);
}
void processAPrice() //
{
int pounds = getPriceInPounds();
int euros = convertPriceIntoEuros(pounds);
int sum = showPriceInEuros(pounds, euros);
calculateSum(euros);
}
int getPriceInPounds() //
{
int priceInPounds;
cout << "Enter a price (in Pounds): /234";
cin >> priceInPounds;
return priceInPounds;
}
int convertPriceIntoEuros(int priceInPounds) //
{
const int conversionRate(0.82);
return priceInPounds / conversionRate;
}
int showPriceInEuros(int pounds, int euros) //
{
SetConsoleOutputCP(1252);
cout << "The Euro value of /234" << pounds << "is: \u20AC" << euros;
}
int calculateSum(int euros) //
{
int sumInEuros;
sumInEuros = (sumInEuros + euros);
return sumInEuros;
}
void produceFinalData(int sum, int numberOfPrices) //
{
SetConsoleOutputCP(1252);
cout << "The total sum is: \u20AC" << sum;
cout << "The average is: \u20AC" << (sum/numberOfPrices);
}
Well, the showPriceInEuros function is not returning the int it promises to return in its signature. That's the error.
If the function is not supposed to return a value, you should declare its return type as void:
void showPriceInEuros(int pounds, int euros);
//^^
and then:
void showPriceInEuros(int pounds, int euros) {
SetConsoleOutputCP(1252);
cout << "The Euro value of /234" << pounds << "is: \u20AC" << euros;
}
of course.
surely it is initialized as I am using it to store a calculation?
The calculation is based on the variable's uninitialised value:
sumInEuros = (sumInEuros + euros);
^^^^^^^^^^ not initialised
Perhaps you could declare it static, so that its value is preserved between calls to the function, in order to calculate the sum of all the values you pass to the function. Usually, it would be better to use a class to manage persistent data like this, with member functions to update and access it.
why must this return a value?
Because you say it does:
int showPriceInEuros(int pounds, int euros)
^^^
If it shouldn't return a value, change the return type to void.
You do not initialize sumInEuros in this function. You store a result in it - that's true but to calculate the result you are using the uninitialized value.
int calculateSum(int euros) //
{
int sumInEuros;
sumInEuros = (sumInEuros + euros);
return sumInEuros;
}
Answering the question from below:
I would probably create a class PriceCalculator which has all the functions of your algorithm plus the internal state:
class PriceCalculator {
int m_sumInEuros;
public:
PriceCalculator()
: m_sumInEuros(0) { }
void processAPrice(int price);
int getSumInEuros() const { return m_sumInEuros; }
private:
void updateSum(int priceInEuros);
};
From your main function you should create an object of this type and give it the prices you want to sum. Do not do any console input from your class.
int main()
{
PriceCalculator calc;
char answer('Y');
int numberOfPrices(0);
while (answer = 'Y')
{
int priceInPounds;
cout << "Enter a price (in Pounds): /234";
cin >> priceInPounds;
calc.processAPrice(priceInPounds);
numberOfPrices++;
cout << "Continue? (Y/N)";
cin >> answer;
}
...
You might want to think about adding the numberOfPrices to your calculator class as well. At the end you will do all the operations in your class but the user input and console output outside your class. Your class can be tested automatically this way and is completely independent from the user interface.

C++: Converting Hexadecimal to Decimal

I'm looking for a way to convert hex(hexadecimal) to dec(decimal) easily. I found an easy way to do this like :
int k = 0x265;
cout << k << endl;
But with that I can't input 265. Is there anyway for it to work like that:
Input: 265
Output: 613
Is there anyway to do that ?
Note: I've tried:
int k = 0x, b;
cin >> b;
cout << k + b << endl;
and it doesn't work.
#include <iostream>
#include <iomanip>
#include <sstream>
int main()
{
int x, y;
std::stringstream stream;
std::cin >> x;
stream << x;
stream >> std::hex >> y;
std::cout << y;
return 0;
}
Use std::hex manipulator:
#include <iostream>
#include <iomanip>
int main()
{
int x;
std::cin >> std::hex >> x;
std::cout << x << std::endl;
return 0;
}
Well, the C way might be something like ...
#include <stdlib.h>
#include <stdio.h>
int main()
{
int n;
scanf("%d", &n);
printf("%X", n);
exit(0);
}
Here is a solution using strings and converting it to decimal with ASCII tables:
#include <iostream>
#include <string>
#include "math.h"
using namespace std;
unsigned long hex2dec(string hex)
{
unsigned long result = 0;
for (int i=0; i<hex.length(); i++) {
if (hex[i]>=48 && hex[i]<=57)
{
result += (hex[i]-48)*pow(16,hex.length()-i-1);
} else if (hex[i]>=65 && hex[i]<=70) {
result += (hex[i]-55)*pow(16,hex.length( )-i-1);
} else if (hex[i]>=97 && hex[i]<=102) {
result += (hex[i]-87)*pow(16,hex.length()-i-1);
}
}
return result;
}
int main(int argc, const char * argv[]) {
string hex_str;
cin >> hex_str;
cout << hex2dec(hex_str) << endl;
return 0;
}
I use this:
template <typename T>
bool fromHex(const std::string& hexValue, T& result)
{
std::stringstream ss;
ss << std::hex << hexValue;
ss >> result;
return !ss.fail();
}
std::cout << "Enter decimal number: " ;
std::cin >> input ;
std::cout << "0x" << std::hex << input << '\n' ;
if your adding a input that can be a boolean or float or int it will be passed back in the int main function call...
With function templates, based on argument types, C generates separate functions to handle each type of call appropriately. All function template definitions begin with the keyword template followed by arguments enclosed in angle brackets < and >. A single formal parameter T is used for the type of data to be tested.
Consider the following program where the user is asked to enter an integer and then a float, each uses the square function to determine the square.
With function templates, based on argument types, C generates separate functions to handle each type of call appropriately. All function template definitions begin with the keyword template followed by arguments enclosed in angle brackets < and >. A single formal parameter T is used for the type of data to be tested.
Consider the following program where the user is asked to enter an integer and then a float, each uses the square function to determine the square.
#include <iostream>
using namespace std;
template <class T> // function template
T square(T); /* returns a value of type T and accepts type T (int or float or whatever) */
void main()
{
int x, y;
float w, z;
cout << "Enter a integer: ";
cin >> x;
y = square(x);
cout << "The square of that number is: " << y << endl;
cout << "Enter a float: ";
cin >> w;
z = square(w);
cout << "The square of that number is: " << z << endl;
}
template <class T> // function template
T square(T u) //accepts a parameter u of type T (int or float)
{
return u * u;
}
Here is the output:
Enter a integer: 5
The square of that number is: 25
Enter a float: 5.3
The square of that number is: 28.09
This should work as well.
#include <ctype.h>
#include <string.h>
template<typename T = unsigned int>
T Hex2Int(const char* const Hexstr, bool* Overflow)
{
if (!Hexstr)
return false;
if (Overflow)
*Overflow = false;
auto between = [](char val, char c1, char c2) { return val >= c1 && val <= c2; };
size_t len = strlen(Hexstr);
T result = 0;
for (size_t i = 0, offset = sizeof(T) << 3; i < len && (int)offset > 0; i++)
{
if (between(Hexstr[i], '0', '9'))
result = result << 4 ^ Hexstr[i] - '0';
else if (between(tolower(Hexstr[i]), 'a', 'f'))
result = result << 4 ^ tolower(Hexstr[i]) - ('a' - 10); // Remove the decimal part;
offset -= 4;
}
if (((len + ((len % 2) != 0)) << 2) > (sizeof(T) << 3) && Overflow)
*Overflow = true;
return result;
}
The 'Overflow' parameter is optional, so you can leave it NULL.
Example:
auto result = Hex2Int("C0ffee", NULL);
auto result2 = Hex2Int<long>("DeadC0ffe", NULL);
only use:
cout << dec << 0x;
If you have a hexadecimal string, you can also use the following to convert to decimal
int base = 16;
std::string numberString = "0xa";
char *end;
long long int number;
number = strtoll(numberString.c_str(), &end, base);
I think this is much cleaner and it also works with your exception.
#include <iostream>
using namespace std;
using ll = long long;
int main ()
{
ll int x;
cin >> hex >> x;
cout << x;
}
std::stoi, stol, stoul, stoull can convert to different number systems
long long hex2dec(std::string hex)
{
std::string::size_type sz = 0;
try
{
hex = "0x"s + hex;
return std::stoll(hex, &sz, 16);
}
catch (...)
{
return 0;
}
}
and similar if you need return string
std::string hex2decstr(std::string hex)
{
std::string::size_type sz = 0;
try
{
hex = "0x"s + hex;
return std::to_string(std::stoull(hex, &sz, 16));
}
catch (...)
{
return "";
}
}
Usage:
std::string converted = hex2decstr("16B564");