I'm trying to learn C++ and have this small beginner question:
why does the standardize function not modify its inputs?
To help with the answers, I have posted an executing code at Coliru
here
and the sources of my program below.
Referring to the code, the question would be: why isn't what's
printed after outside the same as what's printed after inside?
#include <cstdlib>
#include <ctime>
#include <algorithm> // std::copy
#include <iostream>
using namespace std;
void standardize(const int n,const float x[],float ave,float sct){
float acc=0.0f,sum=0.0f;
sum=std::accumulate(x,x+n,0.0f);
ave=sum/(float)n;
std::for_each(x,x+n,[&](const float d){acc+=(d-ave)*(d-ave);});
sct=std::sqrt(acc/(float)(n-1));
std::cout << "inside" << std::endl;
std::cout << ave << std::endl;
std::cout << sct << std::endl;
return;
}
int main(){
const int n=1024;
float a2[n];
float part0=0.0f,part1=0.0f;
std::srand(std::time(0));
for(int i=0;i<n;i++) a2[i]=std::rand()/(float)RAND_MAX;
standardize(n,a2,part0,part1);
std::cout << "outside" << std::endl;
std::cout << part0 << std::endl;
std::cout << part1 << std::endl;
}
You are passing ave and sct by values. Your standardize method modifies copies of those arguments, letting unchanged the original ones declared in main()
Consider passing them by reference:
void standardize(const int n,const float x[],float& ave,float& sct)
Related
I'm starting learning c++ and stepped on this problem, trying to make the following calculation: place + (place / 10)² which if place = 90 it should be 171.
#include <iostream>
#include <iomanip>
#include <cmath>
#include "TestFunction.h"
using namespace std;
int main() {
TestFunction test1 ("John", 90);
test1.getInfo();
}
here is the TestFunction header
#include <iostream>
#include <string>
#include <iomanip>
class TestFunction {
public:
TestFunction(std::string userName, int userPlace) {
name = userName;
place = userPlace;
}
int getPlace() {
return place;
}
int getResult() {
return num1;
}
void getInfo() {
std::cout << "Using getPlace():" << getPlace() << std::endl;
std::cout << "Using getResult(): " << getResult() << std::endl;
std::cout << "Using num1: " << num1 << std::endl;
std::cout << "calculate here: " << getPlace() + pow(getPlace() / 10, 2) << std::endl;
}
private:
std::string name;
int place;
int num1 = place + pow(place / 10, 2);
};
and get this result:
Using getPlace():90
Using getResult(): -2147483648
Using num1: -2147483648
calculate here: 171
I really don't know what I am missing when trying to use getResult() or num1, any advice or simple explanation will be welcome, thanks.
You need to keep track of when your calculations are done.
The init of num1 is done earlier than the initialisation of place, which is something to avoid at all cost.
You could move that calculation into the constructor:
TestFunction(std::string userName, int userPlace) {
name = userName;
place = userPlace;
num1 = place + pow(place / 10, 2);
}
There are other ways, but this is probably most accessable to you.
I have a c++ program where I need to pass the square root of a number in a for loop.
#include<random>
#include<iostream>
#include<algorithm>
#include<string>
#include<math.h>
#include <stdlib.h>
#include <windows.h>
#include <ctype.h>
#include <omp.h>
using namespace std;
int main()
{
vector<int>inputDataBits(49); // vector of randomly generated input data bits
#ifdef printDebug
std::cout << "the input data bits are" << endl;
std::cout << "-------------------------" << endl << endl;
int var =49;
const int r=(int)sqrt(var);
float input2d[r][r];
for (int i = 0; i < r; i++)
{
for (int j = 0; j < r; j++)
{
input2d[i][j] = inputDataBits[(j %r) + (i *r)];
std::cout << input2d[i][j] << "\t";
}
std::cout << endl << endl;
}
std::cout << endl << endl;
#endif
return 0;
}
I get an error 'expression must have a constant value'. Is there a way to do this in c++?
This is the purpose of the constexpr keyword (make the value known at compile time).
constexpr int var=49;
constexpr int r=(int)sqrt(var);
Unfortunately, in the documentation sqrt() is not declared as a constexpr function.
Only gcc seems to consider it as constexpr but it is not portable.
The size of an array needs to be known at compile-time.
Instead you can use a std::vector, which has a dynamic size.
std::vector<std::vector<float>> input2d(std::vector<float>(r), r);
I'd like to display some integer with currency index (I mean dot and double zero)
For example like here:
#include <iostream>
int main() {
int w1=700,c1=99,c2=98;
double noh2o=w1*(100.0-c1)/100.0;
double w2=noh2o+noh2o/(100.0-c2)*c2;
std::cout<<w2<<std::endl;
}
If somebody can help me I will be thankful.
You are supposed to do it with the locale library.
Mostly copied from https://en.cppreference.com/w/cpp/io/manip/put_money like so:
#include <iomanip>
#include <iostream>
#include <locale>
int main() {
long double val = 239.9;
std::cout.imbue(std::locale("en_US.UTF-8"));
std::cout << std::showbase
<< "en_US: " << std::put_money(val)
<< std::endl;
return 0;
}
Use std::fixed and std::setprecision.
Try it online!
#include <iostream>
#include <iomanip>
int main() {
int w1=700,c1=99,c2=98;
double noh2o=w1*(100.0-c1)/100.0;
double w2=noh2o+noh2o/(100.0-c2)*c2;
std::cout << std::fixed << std::setprecision(2) << w2 << std::endl;
}
Output:
350.00
When tying to implement mySqrt function in C++, I used the exp() function like this:
int mySqrt(int x) {
// For x = 2147395600
cout << exp(0.5*log(x)) << " "; // It prints 46340
return exp(0.5*log(x)); // But returns 46339
}
I tried to google the reason for this behavior but could not find anything. I even tried using double but still the same output.
Any explanation for this?
With this code
#include <iostream>
#include <cmath>
#include <cstdio>
using std::cout;
int mySqrt(int x) {
// For x = 2147395600
cout << exp(0.5*log(x)) << " "; // It prints 46340
return exp(0.5*log(x)); // But returns 46349
}
int main(void) {
std::cout << mySqrt(2147395600) << "\n";
printf("%.30f\n", exp(0.5*log(2147395600)));
return 0;
}
I got output:
46340 46339
46339.999999999978172127157449722290
It seems the value is rounded when passed to cout while truncated when converted to int.
The following code inserts only one value to the vector col.
The code is extracted from DBMS code base (for importing files), specifically, it is from 1
The code uses void* to be able to read any field type (int, float, and so on).
#include <iostream>
#include <vector>
using namespace std;
void add(std::vector<void*> &col){
reinterpret_cast<std::vector<int>&>(col).push_back( 1);
reinterpret_cast<std::vector<int>&>(col).push_back( 2);
reinterpret_cast<std::vector<int>&>(col).push_back( 13);
}
int main() {
std::vector<void*> col;
add(col);
cout << col.size() << endl;
for(int i=0;i<col.size();i++)
cout <<reinterpret_cast<std::vector<int>&> (col)[i] <<endl;
return 0;
}
I am not sure how this code work?
Your code is exhibiting undefined behavior.
std::vector<void*> and std::vector<int> are two completely separate and unrelated types, you can't safely cast between them the way you are, especially since there is no guarantee that void* and int are the same byte size.
Cast the values you are pushing, don't cast the vector itself, eg:
#include <iostream>
#include <vector>
#include <cstdint>
using namespace std;
void add(std::vector<void*> &col) {
col.push_back(reinterpret_cast<void*>(static_cast<intptr_t>(1)));
col.push_back(reinterpret_cast<void*>(static_cast<intptr_t>(2)));
col.push_back(reinterpret_cast<void*>(static_cast<intptr_t>(13)));
}
int main() {
std::vector<void*> col;
add(col);
cout << col.size() << endl;
for(int i=0;i<col.size();i++)
cout << reinterpret_cast<intptr_t>(col[i]) << endl;
return 0;
}
Of course, you really should be using the proper container type to begin with:
#include <iostream>
#include <vector>
using namespace std;
void add(std::vector<int> &col) {
col.push_back(1);
col.push_back(2);
col.push_back(13);
}
int main() {
std::vector<int> col;
add(col);
cout << col.size() << endl;
for(int i=0;i<col.size();i++)
cout << col[i] << endl;
return 0;
}