I need to round the answer 23.428 and get 23.4.
I did a little search about it and I may need to include a line float round (s) but I did it and CODEBLOCKS gives me an error.
Note: the file Information.txt contains numbers 7.5 305.5 4.09 4
My code is:
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
int main()
{
float m, k, kk;
int n;
float s;
ifstream fd("Information.txt");
fd >> k >> m >> kk >> n;
k = k / 100;
m = m * k;
kk = kk * m;
s = kk / n;
/*s=((((k/100)*m)*kk)/n);*/
fd.close();
ofstream fr ("Rezults.txt");
fr << s;
fr.close();
return 0;
}
You can just multiply the number by 10, round it and then divide by 10 again:
float x = 23.428;
x = std::round(10.0*x);
x /= 10.0;
Floating-point values (i.e. floats) usually aren't stored in base 10, but when you display their values they get converted to base 10 because that's what most of us are used to. Output streams (std::cout and the fr in the example) do this conversion, with a default precision of 6 digits. To display 3 digits, just change the precision:
#include <iostream>
#include <iomanip>
#include <fstream>
int main() {
float num = 23.428;
std::cout << std::setprecision(3) << num << '\n';
std::ofstream fr("Rezults.txt");
fr << std::setprecision(3) << num << '\n';
return 0;
}
Related
#include <iostream>
#include <stdio.h>
#include <string>
#include <cstring>
#include <fstream>
using namespace std;
int main()
{
int masivs[24], x = 0, y = 0;
int negativi[20];
int pozitivi[20];
ifstream f;
f.open("f.txt");
while (f.good() && x < 24)
f >> masivs[x++];
f.close();
cout << masivs[1];
ofstream f2("f2.txt");
ofstream f1("f1.txt");
for (x = 0; x < 24; x++)
if (masivs[x] >= 0)
pozitivi[x] = masivs[x];
else
negativi[x] = masivs[x];
for (int k = 0; k < 8; k++)
{
f2 << negativi << endl;
}
for (int k = 0; k < 15; k++)
{
f1 << pozitivi << endl;
}
}
Ive been trying to find out how to do this for 2 days and im going crazy. Just please tell me how to do it. Im trying to divide the f.txt file numbers into f1.txt with the positives and f2.txt with the negatives. I have to read the f file with an array adn then write the positives in f1 and negatives in f2. and all the zeros in f3. Pls help ive been trying to find info on this but i cant do it.
the f.txt numbers:
-9
-8
-7
-6
-5
-4
-3
-2
-1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
You have two major problems. One benign and one which leads to undefined behavior.
The benign problem is the statement
f2<<negativi<<endl;
This is exactly the same as
f2 << &negativi[0] << endl;
In other words, it writes a pointer to the first element of negativi.
The more serious problem is a buffer overflow in the loop
for (x = 0; x < 24; x++)
if (masivs[x] >= 0)
pozitivi[x] = masivs[x];
else
negativi[x] = masivs[x];
Here you use the same index x for both pozitivi, negativi and masivs. This index is only valid for masivs.
The loop as it works now with a single index x will not only put holes in the pozitivi and negativi arrays, but also go out of bounds of both.
The solution is to add another index, one each for the pozitivi and negativi arrays:
unsigned p = 0; // Index for positive number array
unsigned n = 0; // Index for negative number array
for (unsigned x = 0; x < 24; x++)
{
if (masivs[x] >= 0)
pozitivi[p++] = masivs[x];
else
negativi[n++] = masivs[x];
}
Afterwards you can use p and n as sizes for the corresponding array, to use when you write the result to the files.
And as mentioned in a comment to the question, the arrays aren't really needed which makes much of the code moot, and the whole program much simpler. And simplicity is better, as there's less chance of errors.
You can do a simple while(getline()) loop...
#include <iostream>
#include <stdio.h>
#include <string>
#include <cstring>
#include <fstream>
int main()
{
int lineNumber, it = 0;
std::string line;
std::ifstream f("f.txt");
std::ofstream f1, f2;
f1.open("f1.txt");
f2.open("f2.txt");
while(std::getline(f, line)) //reads each line of f.txt ino a string
{
try
{
lineNumber = std::stoi(line);
}
catch(std::invalid_argument& e) //if value is not a number
{
std::cout << "VALUE IS NOT A NUMBER ON ITERATION " << it << '\n';
//std::abort();
continue;
}
catch(std::out_of_range& e) //if value is above +-2^32 +-1
{
std::cout << "VALUE OUT OF RANGE ON ITERATION " << it << '\n';
//std::abort();
continue;
}
if(lineNumber > 0)
{
f1 << lineNumber << '\n';
}
else
{
f2 << lineNumber << '\n';
}
it++;
}
f1.close();
f2.close();
}
This will get your desired output, file f1.txt containing all the positive numbers, and file f2.txt containing all the negative numbers.
Quick question. This is the code that I wrote to finish a problem in SPOJ. The output is correct but it gives me wrong answer. Whats wrong with my code? This is the link to the question: https://www.spoj.com/problems/SUMUP/
#include <iostream>
#include <iomanip>
using namespace std;
void cal(int n){
long double a, b, c;
a = (n*n) + n;
b = 2.0 *(n*n + n + 1.0);
c = a / b;
cout<< setprecision(5) << c << '\n';
}
int main()
{ int n, z, t;
scanf("%d", &t);
const int NUMS = t;
int bobo[NUMS];
for(z = 0; z < NUMS; z++){
scanf("%d", &bobo[n]);
cal(bobo[n]);
}
return 0;
}
This is the input:
5
1
2
3
4
5
This is my output:
0.33333
0.42857
0.46154
0.47619
0.48387
In the lines:
for(z = 0; z < NUMS; z++){
scanf("%d", &bobo[n]);
cal(bobo[n]);
}
You should use z instead of n when calling scanf() and cal()
SPOJ expected output seems to require trailing zeroes, which the setprecision(5) function removes from c output if there's any. To keep the trailing zeroes you can add left << setfill('0') << setw(7) in your cout to indicate that there should be at least 7 characters presents in your output line (two characters for '0.' and 5 decimal places) and if there're fewer characters, it will fill to the left side with '0's, adding back the trailing zeroes required.
cout << left << setfill('0') << setw(7) << setprecision(5) << c << '\n';
Another more elegant solution is to use printf instead
printf("%.5Lf\n",c);
void cal(int n){
long double a, b, c;
a = (n*n) + n;
b = 2.0 *(n*n + n + 1.0);
c = a / b;
printf("%.5Lf\n",c);
}
After calculating a number, I need to get several digits of this one. I cast it to string, and print a digit, but in one piece of code, it works correct (prints only one digit), but after I equate it to another variable, the program prints 2 digits.
#include "stdafx.h"
#include <iostream>
#include <chrono>
#include <ctime>
#include <sstream>
using namespace std;
int main()
{
time_t seconds;
int res = 0;
seconds = time(NULL);
double nump = seconds;
cout.precision(45);
for (int i = 1; i <= 100; i++) {
nump = nump /10;
}
std::ostringstream strs;
strs.precision(55);
strs << nump;
std::string str = strs.str();
cout << str[str.size() - 9] << endl; // here we get a gidit from the string (e.g. 5)
res = str[str.size() - 9];
cout << res << endl; // here we get a number (e.g. 49)
system("pause");
return 0;
}
I cant understand whats going on. Please help!
That's because here
res = str[str.size() - 9];
You are storing the value of a char in an int. Printing the same value as int can have different results when you send it to std::cout than when you print it as char. For integers this operator is called, while for chars this operator is called instead.
In your example, you probably have a value of '1' (which is 49 in ASCII). When you print it as a char it prints 1, and when you print it as an int, it prints 49.
One way to solve this problem is to make int res be a char instead.
Screenshot of the outputs i got for the codeHow to code to separate the whole part and decimal part
I wrote this code but it gives different values at times. I don't know why?
#include <iostream>
using namespace std;
int main()
{
float f, a, b;
int x, y, c;
cout << "enter the float value" << endl; cin >> f;
x = (int)f; cout << "before " << x;
a = b = f;
c = 1;
while (b != int(a))
{
b = b * 10;
a = a * 10;
c = c * 10;
}
y = (f * c) - (x * c);
cout << "after " << y;
}
enter the float value
22.47
before 22 after 46
user#user:~/cpp$ ./a.out
enter the float value
2234.127
before 2234 after 126
user#user:~/cpp$ ./a.out
enter the float value
22.335
before 22 after 334
user#user:~/cpp$ ./a.out
enter the float value
222.88
before 222 after 88
these are a few values i tried.
How to code to separate the whole part and decimal part?
I assume that you want to only represent the floating value into non-decimals part and decimals part. In that case, take the user input as an std::string, and do as follows. I hope the comments will get you through the code:
(See live example)
#include <iostream>
#include <string>
#include <cstddef> // std::size_t
int main()
{
std::cout << "enter the float value\n";
std::string strInput; std::cin >> strInput; // take the user input as std::string
std::size_t pos{ 0 };
// find the position of charector decimal point('.') using std::string::find
pos = strInput.find(".", pos);
// if the decimal point is found in the user input: x = substring starting from 0 to pos of user input.
const std::string x = pos != std::string::npos ? strInput.substr(0, pos) : strInput;
// if the decimal point is found in the user input: y = substring starting from pos + 1 to end of user input.
const std::string y = pos != std::string::npos ? strInput.substr(pos + 1) : std::string{ "" };
std::cout << "before " << x << " after " << y << '\n';
return 0;
}
sample input:
enter the float value
0123.04560
Output:
before 0123 after 04560
PS: However, like in the example given above, having zero before the separated decimal parts(both 0123 and 04560) might be unwanted. In that case, use any of the standard functions to convert them back to integers or remove zeros from from the beginning using erase-remove idiom.
I'm coding a program that takes user inputs and get the average of it. I need the average to always have three decimal points.
float didn't work.
some tutorials online advised to use setprecision() and fixed. That won't work because I don't know how long the number is gonna be.
Do you recommend converting the number into a string, get the length, and convert it back to double and use: setprecision(string.length+3)
Thanks
Try this :
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
float ex[] = { 0.12345, 1.2345, 12.345};
cout << setprecision(3) << fixed;
for(int i = 0; i < 3; ++i)
cout << ex[i] << endl;
return 0;
}
which gives the following output:
0.123
1.235
12.345
I recommend using the full precision of double during your calculations, and then display your final result with three decimal places.
#include <iostream>
#include <iomanip> // header file for setprecision()
using namespace std;
int main()
{
double input[4] = {1.000 , 2.0000 , 3.00 , 5.235 };
double answer = 0 , sum = 0 ;
int count = 0;
for(int i = 0; i < 3; ++i)
{
sum+=input[i];
count++;
}
answer = sum/count;
cout.precision(3);
cout << answer << endl;
return 0;
}