#include <iostream>
using namespace std;
void reset(int *a, int *b){
int sum = *a + *b;
*a = (sum / 2.0 - sum / 2) >= 0.5 ? sum / 2 + 1 : sum / 2;
*b = *a;
cout << hex << (void *)a<<endl;
cout << hex << b<<endl;
}
int main(){
int a, b;
cin >> a >> b;
reset(&a, &b);
cout << a <<' '<< b << endl;
}
I use the code to reset two variable,but after I print the pointers of variable,the data changed.When I commente the two cout statement.It works.
Looks like this:
You should return to dec, because you changed the output to hex
#include <iostream>
using namespace std;
void reset(int *a, int *b){
int sum = *a + *b;
*a = (sum / 2.0 - sum / 2) >= 0.5 ? sum / 2 + 1 : sum / 2;
*b = *a;
cout << hex; //set hex for output stream
cout << (void *)a<<endl;
cout << b<<endl;
cout << dec; // return to dec system
}
int main(){
int a, b;
cin >> a >> b;
reset(&a, &b);
cout << a <<' '<< b << endl;
}
Variables are not modified, you change basefield format flag after using std::hex here:
cout << hex << (void *)a << endl;
cout << hex << b << endl;
That's why commenting this out "fixes" this "problem".
You can uncomment this call, but modify you reset() function, so it will restore original stream state:
void reset(int *a, int *b)
{
int sum = *a + *b;
*a = (sum / 2.0 - sum / 2) >= 0.5 ? sum / 2 + 1 : sum / 2;
*b = *a;
cout.setf(std::ios::hex); //Print as hexadecimal numbers
cout << (void *)a << endl;
cout << b << endl;
cout.setf(std::ios::dec); //Restore to decimal
}
I modified your reset to set hex only once instead of doing << hex every time you print something (although it is not necessary, because, as you noticed, stream is modified permanently - that's why I prefer explicit functions call).
Further read: std::ios_base::setf.
Related
This question already has answers here:
How does the function pow work?
(2 answers)
Closed 4 years ago.
I'm doing algorithm for solving Quadratic equation.
I type for A = 4, B = 10, C = 4 which gives value of 36 for delta.
My issue is that
int delta;
returns value of 35, and
double delta;
returns value of 36.
I'm using Atom text editor, rest of code is below.
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int a,b,c;
int delta;
int x1, x2;
cout << "Rownanie kwadratowe w postaci ax^2 + bx + c = 0" << endl;
cout << "Podaj wartosc A" << endl;
cin >> a;
cout << "Podaj wartosc B" << endl;
cin >> b;
cout << "Podaj wartosc C" << endl;
cin >> c;
delta = pow(b,2) - (4 * a * c);
cout << "Delta = " << delta << endl;
return 0;
}
It works for me. Bellow code is much shorter and better for the Minimum example, isn't it?
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int a = 4, b = 10, c = 4;
int delta = pow(b,2) - (4 * a * c);
cout << "Delta = " << delta << endl;
return 0;
}
If you use integral arithmetic then use integral not floating point operations. The problem consists of floats. Result of pow(b, 2) may be like 99.99999999997, that rounded down to int is 99.
#include <iostream>
using namespace std;
int main()
{
int a = 4, b = 10, c = 4;
int delta = b * b - (4 * a * c);
cout << "Delta = " << delta << endl;
return 0;
}
I am learning C++ and came upon this problem while trying to use a formula to calculate the current.
And I got: 0.628818 where the answer should be:
f=200 Hz
R=15 Ohms
C=0.0001 (100µF)
L=0.01476 (14.76mH)
E = 15 V
Answer: I = 0.816918A (calculated)
Below is my code:
#include <iostream>
#include <cmath>
int main()
{
const double PI = 3.14159;
double r = 15;
double f = 200;
double c = 0.0001;
double l = 0.01476;
double e = 15;
double ans = e / std::sqrt(std::pow(r, 2) + (std::pow(2 * PI*f*l - (1.0 / 2.0 * PI*f*c), 2)));
std::cout << "I = " << ans << "A" << std::endl;
}
I have read about truncation errors and tried to use 1.0/2.0 but doesn't seem to work either.
Truncation error refers to using only the first N terms of an infinite series to estimate a value. So the answer to your question is "No." You might find the following to be of some interest however....
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
template<typename T>
T fsqr(T x) { return x * x; }
// Numerically stable and non-blowuppy way to calculate
// sqrt(a*a+b*b)
template<typename T>
T pythag(T a, T b) {
T absA = fabs(a);
T absB = fabs(b);
if (absA > absB)
{
return absA*sqrt(1.0 + fsqr(absB / absA));
} else if (0 == absB) {
return 0;
} else {
return absB*sqrt(1.0 + fsqr(absA / absB));
}
}
int main () {
double e, r, f, l, c, ans;
const double PI = 3.14159265358972384626433832795028841971693993751058209749445923078164062862089986280348253421170;
cout << "Insert value for resistance: " << endl;
cin >> r ;
cout << "Insert value for frequency: " << endl;
cin >> f;
cout << "Insert value for capacitance: " << endl;
cin >> c;
cout << "Insert value for inductance: " << endl;
cin >> l;
cout << "Insert value for electromotive force (voltage): " << endl;
cin >> e;
ans = e / pythag(r, 2*PI*f*l - (1/(2*PI*f*c)) );
cout << "I = " << ans << "A" << endl;
system("pause");
return 0;
}
Just kidding about all that PI.
The main problem is multiplying ½ by πfC instead of dividing, here:
(1.0 / 2.0 * PI*f*c)
This sort of problem is best avoided by using suitable named values (that also allows you to use faster and more precise x*x instead of std::pow(x,2)).
You can also remove some of that arithmetic by using the standard hypotenuse function instead of squaring and sqrting inline:
double ans = e / std::hypot(r, (2*PI*f*l - 0.5/PI/f/c));
#include <iostream>
#include <cmath>
int main()
{
static constexpr double PI = 4 * std::atan(1);
double r = 15; // ohm
double f = 200; // hertz
double c = 0.0001; // farad
double l = 0.01476; // henry
double e = 15; // volt
double current = e / std::hypot(r, (2 * PI*f*l - 0.5/PI/f/c));
std::cout << "I = " << current << "A" << std::endl;
}
I'm currently doing a program which calculates the scalarProduct (Dot Product) using templates and I've run into a problem with two things.
One being: How to declare a template and call it from main.
Two being: How to pass Arrays to functions.
Any help is appreciated, thanks
// scalarProduct.cpp : Defines the entry point for the console application.
//
#include <iostream>
#include <math.h> /* sqrt */
using namespace std;
template<typename T>
void scalarProduct(T a[], T b[])
{
T a[3];
T b[3];
this->a[] = a;
this->b[] = b;
T axb;
T roota;
T rootb;
T result;
axb = ((a[0] * b[0]) + (a[1] * b[1]) + (a[2] * b[2]));
roota = sqrt((a[0] * a[0]) + (a[1] * a[1]) + (a[2] * a[2])); // the formula for the Euclidean length of the vector A.
rootb = sqrt((b[0] * b[0]) + (b[1] * b[1]) + (b[2] * b[2])); // the formula for the Euclidean length of the vector B.
result = axb / roota * rootb;
cout << "Result: " << result;
};
int main()
{
int a[3];
int b[3];
cout << "Enter A: " << endl; // Vector A Input
cout << "X:";
cin >> a[0];
cout << "Y:";
cin >> a[1];
cout << "Z:";
cin >> a[2];
cout << "Ennter B: " << endl; // Vector B Input
cout << "X:";
cin >> b[0];
cout << "Y:";
cin >> b[1];
cout << "Z:";
cin >> b[2];
scalarProduct(a[], b[]);
system("pause");
return 0;
}
For the template part of the question:
Heres the format for declaring and defining a template function:
template<compileTimeParameters>
returnType functionName(functionParameters) {
...;
}
and invoke it like this:
functionName<compileTimeParameters>(functionParameters);
For example, if you wanted a function that printed with cout whatever you gave it, go like this:
template<typename T>
void println(T value) {
std::cout << value << std::endl;
}
and invoke like this:
int main() {
//string
println<std::string>("yo yo yo print a newline");
//integer
println<int>(420);
//some other random type
println<myType>(someInstanceOfMyType);
}
And if the compiler can deduce the template parameters by the function parameters, you don't have to specify anything explicitly inside the <> brackets. For example:
int main() {
//compiler deduces that you are passing a const char[]
println("the compiler can figure out what I mean");
}
In scalarProduct() get rid of your local arrays a and b -- you are getting them from the parameters passed into the function. Also, scalarProduct is a function, not the method of a class, so there is no "this" to reference.
In main() just call:
scalarProduct(a, b);
It should work then.
Your problem is not with templates, but with C++ basics, like passing array to a function.
// scalarProduct.cpp : Defines the entry point for the console application.
//
#include <iostream>
#include <math.h> /* sqrt */
using namespace std;
template<typename T>
void scalarProduct(T a[], T b[])
{
/*
* remove this
T a[3];
T b[3];
this->a[] = a;
this->b[] = b;
*/
T axb;
T roota;
T rootb;
T result;
axb = ((a[0] * b[0]) + (a[1] * b[1]) + (a[2] * b[2]));
roota = sqrt((a[0] * a[0]) + (a[1] * a[1]) + (a[2] * a[2])); // the formula for the Euclidean length of the vector A.
rootb = sqrt((b[0] * b[0]) + (b[1] * b[1]) + (b[2] * b[2])); // the formula for the Euclidean length of the vector B.
result = axb / roota * rootb;
cout << "Result: " << result;
};
int main()
{
int a[3];
int b[3];
cout << "Enter A: " << endl; // Vector A Input
cout << "X:";
cin >> a[0];
cout << "Y:";
cin >> a[1];
cout << "Z:";
cin >> a[2];
cout << "Ennter B: " << endl; // Vector B Input
cout << "X:";
cin >> b[0];
cout << "Y:";
cin >> b[1];
cout << "Z:";
cin >> b[2];
//scalarProduct(a[], b[]);
scalarProduct(a, b);
system("pause");
return 0;
}
Also if you dealing with three dimensional points I think it would be a good idea to create struct Point or class Point. If you want your functions to deal with vectors, then use pointers or better std::vector.
The input for a,b,c are 25,27.5,40.
The correct answer that should be displayed is 754573.2, but I continue getting 754573.17 despite reading about how to solve this. I also am not allowed to use setprecision() to solve the issue.
What am I doing wrong?
#include <iostream>
using namespace std;
int main() {
double a, b, c;
double g;
double v;
double ci = 123.00;
double i = 15;
cout << "enter the 3 values: ";
cin >> a >> b >> c;
a = a * i;
b = b * i;
c = c * i;
v = a * b * c;
g = static_cast<int>(v / ci * 100 + .5) / 100.0;
cout << "The answer is " << g;
return 0;
}
Thanks everyone! I got it to work.
cout is using a default precision, and that is why the output is rounded to 5 digits.
To see that, call cout::precision();
A cheesy answer to try is using sprintf:
char *result = char[256];
sprintf(&result, "%.2lf", g);
cout << result;
int g = static_cast<int>(v / ci);
int h = static_cast<int>((100 * v / ci) + 0.5);
int i = h - g * 100;
cout << "The answer is " << g << "." << i << "\n";
I am having trouble with the following line of code:
double answer;
answer = num[count] / den[count]
cout << " Fraction" << count + 1 << " " << num[count]
<< " / " << den[count] << " = " << answer << endl;
How come my rendition of answer is not working? Am I overlooking something? I am using arrays and am getting the data from a separate text file. When I use the code above I get the numbers that are to be divided correctly but the answer is incorrect. It comes out to be a random number usually 0 or 1.
Here is my code:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
using namespace std;
void read_data(int num[], int den[], int size);
void showValues(int num[],int den[], int size);
int main()
{
const int size1 = 12;
const int size2 = 12;
ifstream dataIn;
int num[12];
int den[12];
read_data(num,den,size1);
cout << "Here are the fractions: " << endl;
showValues(num,den,size1);
system("PAUSE");
return 0;
}
void read_data(int num[], int den[], int size)
{
ifstream dataIn;
dataIn.open("walrus.txt");
if( dataIn.fail() )
{
cout << "File does not exist." << endl;
exit(1);
}
int count;
for ( count = 0; count < size; count++ )
{
dataIn >> num[count];
}
for (count = 0; count < size; count++)
{
dataIn >> den[count];
}
dataIn.close();
}
void showValues(int num[],int den[], int size)
{
int count;
for (count = 0; count < size; count++)
{
if (den[count] == 0)
{
cout << " Fraction" << count + 1 << " "
<< num[count] << " /" << den[count]
<< " Is invalid" << endl;
}
else
{
double answer;
answer = num[count] / den[count];
cout << " Fraction" << count + 1 << " "
<< num[count] << " / " << den[count]
<< " = " << answer << endl;
}
}
}
#main ifstream dataIn;
You are not using this object
#function read_data :
int count;
for ( count = 0; count < size; count++ )
{
dataIn >> num[count];
}
for (count = 0; count < size; count++)
{
dataIn >> den[count];
}
Assuming ur file looks like :
1 2 23 32 44 // numerators
2 3 1 99 24 // den
The proper way to read is :
int count = 0;
while( count < size && dataIn >> num[count++] ) // numerators
;
count = 0;
while( count < size && dataIn >> den[count++] )
;
#function showValues :
try changing
double answer;
answer = num[count] / den[count];
cout << " Fraction" << count + 1 << " "
<< num[count] << " / " << den[count]
<< " = " << answer << endl;
to :
double answer = static_cast<double>(num[count]) / den[count];
cout << " Fraction" << count + 1 << " "
<< num[count] << " / " << den[count] << " = " << answer << endl;
In C and C++, if you do,
double answer = 10 / 3;
your answer will be 3. The reason is you have 2 integers and an integer division will take place. The resulting output is then implicitly converted into a double. So the steps are,
double answer = 10 / 3
double answer = 3
double answer = 3.0
To fix this, you tell the compiler that you want this to be treated as floating point division.
double answer = 10.0 / 3;
This works by,
double answer = 10.0 / 3
double answer = 10.0 / 3.0
double answer = 3.33333333...
The compiler will implicitly cast the 3 into a larger double type, 3.0.
So in your code, you have to convert integer division into floating point division by casting at least one of the division arguments into a double.
double foo = num[count] / den[count];
simply becomes
double foo = num[count] / static_cast<double>(den[count]);
Alternatively, if one or both of the arrays were of double type, you would not have this problem requiring casts.