Related
I am trying to print a number up to say 5 decimal places.
I have:
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
float a = 987.65;
float b = 1.23456789;
scanf("%f %f", &a, &b);
printf("%.5f %.5f", a, b);
return 0;
}
I get the result as 987.65000 and 1.23456
I want the result to be 987.65 and 1.23456, so basically I want up to 5 i.e <=5 decimal digits in my answer.
A slightly less technical way to do it would be using setprecision, as displayed below:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float a = 987.65;
float b = 1.23456789;
cout << setprecision(5);
cout << a << " " << b << endl;
return 0;
}
Output:
987.65 1.2346
The fundamental problem is that a computer can't exactly represent most floating point numbers.
Also, you want a complex formatting rule: if ending digits are zero, print spaces.
The problem is that your number 987.65000 could be represented as 98.6500001 and so wouldn't work with your formatting rule.
I believe you will have to write your own formatting function to achieve the functionality you are looking for.
Here's a solution that does what you want:
#include <iostream>
#include <cstdio>
using namespace std;
unsigned int numPlaces = 5; //number of decimal places
unsigned int determinePlaces (float number) {
unsigned int myPlaces = 0;
while (number != (int)(number) && myPlaces<=numPlaces-1) {
number = number*10;
myPlaces++;
}
return myPlaces;
}
int main() {
float a = 987.65;
float b = 1.23456789;
printf("%.*f %.*f\n", determinePlaces(a), a, determinePlaces(b), b);
return 0;
}
Output:
987.65 1.23457
Basically, the code keeps on multiplying the goat by 10 until the cast to an integer (essentially taking the floor value) matches the float. If it doesn't when it reaches the fifth multiplication by 10, we satisfy ourselves with a printf of 5 decimal places. Otherwise, we print the amount that was necessary to make the match to the floor value.
The task is: I have number a=2.7182818284590452353602875.
It is 25 digits after comma. I need to write a program which will round this number to the specified precision.
The precision is constrained to be 0 < n < 100.
For example:
Input: 0
Output: 3
Input: 25
Output: 2.7182818284590452353602875
Input: 4
Output: 2.7183
and so on.
This is my code. It works fine, BUT I am going out of the unsigned long long range if n>17...
#include <iostream>
#include <iomanip>
#include <cmath>
#include <math.h>
using namespace std;
int main()
{
double a=2.7182818284590452353602875;
double b=a;
unsigned long long c=a;
int n;
int kiek=0;
cin>>n;
while (1!=0){
b=b*10;
c=b;
if (kiek==n) break;
kiek++;
cout<<c<<endl;
}
cout<<c<<endl;
if((c%10)>4) {c=c/10+1;}
else {c=c/10;}
double atgal=1;
for(int i=0;i<n;i++){
atgal*=10;
}
cout<<endl<<atgal<<endl;
b=c;
b=b/atgal;
cout<<fixed<<setprecision(n)<<b;
}
Any suggestions about how to improve it or make it work?
The basic problem is this: The maximum accuracy of a double is about 17 digits. Even if you write double a=2.7182818284590452353602875; the last digits are ignored.
If you really need up to 100 digits og accuracy, you have to use a special library, one of these (GMP) has been mentioned in the comments.
If you do not need higher accuracy and only the output format is important for you, use this:
std::cout << std::setprecision(n) << a;
This can be done with printf precision setting:
printf("%.*f", precision, value);
The output should be rounded (not just truncated) value according to the C++ and C standards (C:7.21.6.1.8: "The value is rounded to the appropriate number of digits.").
Same result can be achieved using iostreams:
std::cout << std::fixed << std::setprecision(precision) << value;
If you want to implement it yourself, you can do so without ever converting the value to an integer, e.g. using functions such as ceil(), floor(), or modf().
Note that you can print an integer value stored in a float or double by printing it with the precision set to 0.
You can start of with the following code (no rounding, just truncating) and modify it to your needs.
double integerPart = 0;
double fractionalPart = 0;
// print the integer part
fractionalPart = modf(value, &integerPart);
printf("%.0f", integerPart);
// print the decimal point
printf(".");
// print the fractional part digit by digit
for (int i = 0; i < precision; ++i) {
fractionalPart *= 10;
fractionalPart = modf(fractionalPart, &integerPart);
printf("%.0f", integerPart);
}
Found new solution by myself ^^"
#include <iostream>
using namespace std;
int main()
{
int sk[25]={7,1,8,2,8,1,8,2,8,4,5,9,0,4,5,2,3,5,3,6,0,2,8,7,5};
int n=0;
cin>>n;
if(n==0) cout<<3;
else if (n==25) {
cout<<2<<".";
for(int i=0;i<n;i++){
cout<<sk[i];
}
}
else{
if (sk[n]>4){
if(sk[n-1]==9){
sk[n-1]=0;
sk[n-2]++;
}
else sk[n-1]++;
}
cout<<2<<".";
for(int i=0;i<n;i++){
cout<<sk[i];
}
}
return 0;
}
Thanks everyone for your replies!!! ^^
What this code does now: I give int values and it calculates the average between them.
What Ive spent hours on trying to get it do: Ive tried making it so that it would calculate the average between double values. Ive tried everything but it always fails or goes into an infinite loop or will not compile.
Question: So how should I modify my code to make it work with double values/numbers?
#include <stdio.h>
void main()
{
int Tau[10]={0,0,0,0,0,0,0,0,0,0};
int r, i = 0;
int m = 0;
int huku = 0;
do{
printf("Enter numbers: ");
scanf_s("%d", &i);
Tau[m]+=i;
huku++;
}while(i != 0);
r = (Tau[m]/(huku-1));
printf("The average of your numbers is; %d\n", r);
}
You have some issues in your code but basically, integer division will not give you doubles. The result of an integer divided by an integer is another integer, not a double. If you want doubles you need to cast either the numerator or denominator to a double and store the result in a double.
Welcome to Numerical Analysis 1001.
Integer math:
2 / 3 = 0;
4 / 2 = 2;
5 / 2 = 2;
Integers don't do fractions.
I don't see why you need Tau to be a vector in your case. An int would suffice.
huku-1 -> That is wrong. It should be just huku.
You need to cast Tau and huku to double when you divide. It won't hurt to check that huku is != 0 also.
m is useless. Just delete it.
r shouldn't be an int if you wish to store Tau/huku in it.
in printf replace %d with %lf
The simplest changes only involve four lines:
double Tau[10] = {0,0,0,0,0,0,0,0,0,0};
double r, i = 0;
scanf_s("%f", &i);
printf("The average of your numbers is; %f\n", r);
Note that this doesn't address the coding issues; all it does is change the code to read and work with double instead of int.
double r = 0;
int i = 0;
r = ((double)Tau[m]/((double)huku-1));
printf("The average of your numbers is; %f\n", r);
// Question is tagged for C++, but the code is in C.
// I will change your code a bit, because you had quite a few mistakes.
#include <stdio.h>
void main ()
{
int sum = 0; // sum of all numbers you entered, to find average you only need total sum and number of entries
int numOfEntries; // number of entries (numbers taken from input)
int inputNum; // variable where you will write numbers from input one by one
double average; // Not really needed, but it can help to simplify the problem to you.
printf("Enter numbers: ");
do
{
scanf_s("%d", &inputNum);
sum += inputNum;
numOfEntries++;
} while (inputNum != 0); // I understand you read numbers until you read value 0.
// int / int will give you rounded number, not the true average, so we need to convert one of the operands to a real number, in this case double
// double / int or int / double will give you a real number as result, which will have true average value, and that is why I converted sum to a real number
if (numOfEntries != 0)
average = (double)sum / numOfEntries;
else
average = 0;
printf("The average of your numbers is; %f\n", average); // Here I did it again - print double instead of int to get true value.
}
It will be even easier to change this:
....
double sum = 0;
...
average = sum / numOfEntries; // Here sum is already double, not int, so you don't need to change it manually.
...
Now, if you want to make it work for double, the only difference will be:
double sum = 0;
double inputNum;
scanf_s("%lf", &inputNum);
average = sum / numOfEntries;
So, to round up the story - you have variable to input a number from keyboard, a variable which holds sum of all entered numbers so far, a variable which counts how many numbers you entered from keyboard. You input numbers until you enter 0 as value, then the program will exit the loop. Formula for average number is sum of all divided by number of numbers. With integers you have to add conversion to a real number or otherways you won't get accurate result.
I hope I didn't confuse you. :D
im simple asking if this is ok. i was asked to do the following. Write a program that will continuously ask the user for positive integers (until the
user enters a negative integer at which the program will be terminated). Every
time the user inputs a positive integer the program will print out this integer in
reverse. Your program should have a function that accepts and integer and returns
an integer in reverse. To convert the integer to its reverse, your program will call
this function. at the end of each output i keep getting 0. please explain why. also if i use void main with the function i get garbage. please explain why. thanks in advance
this is my code....
#include<iostream>
#include<cstdlib>
using namespace std;
int reverseNum(int num){
for(int j=num; j>0; j--)
cout<<j<<" ";
cout<<endl;
return false;
}
int main(){
double enternum = 0;
do{
cout<<"Enter a positive number > 0, to begin countdown ";
cin >>enternum;
cout<<reverseNum(enternum);
cout<<endl;
}
while(enternum>0);
if(enternum<=0)
cout<<"Invalid entry, good bye.";
cout<<endl;
return 0;
}
because of this: return false; - I'll leave it to you to figure out the rest..
The function is supposed to reverse the integer and then return the result. For example, if the input is 123, then the function returns 321.
Your function outputs a count-down and returns 0 (=false).
To reverse a number, you can a) convert it to string, reverse the string, convert it back to integer; b) do it on integers directly with mathematical division / multiplication / addition / modulo operations.
In C++, you don't use void main().
A 0 because when you return false, the result of type bool is implicitly converted to an int and gets printed at the line cout<<reverseNum(enternum);
Also, In this line, double enternum = 0; you want an integer int.
From your text I thought the program was working as intended, but from reading the code I suppose it just counts down from the number. Was this what you wanted?
I'd have implemented it like this (and here the function returning an integer makes sense too):
int reverseNum(int num)
{
int reverse = 0;
[...] // Do the actual reversing
return reverse;
}
Your program should have a function that accepts and integer and returns an integer in reverse
your reverseNum function should return the reversed integer, not false. and it shouldn't print the number as well, it's the caller which supposed to print it.
if one does:
i = reverseNum(1234);
then i should contain 4321 as an integer (NOT string).
the reason you keep getting 0 is because false is equivalent to 0 as an integer.
You should read the C++ FAQ in its entirety. You should especially read this. You should also learn how to debug your code. If you stepped through your code in a debugger then all the answers that you have been given here will be obvious.
For good fun, I attempted a generic implementation that supports any integral or floating point type supported by your compiler.
Be warned, there are a number of issues:
reversing a floating point number is not well defined semantically (how to position the decimal separator? How do we handle exponential notation?)
floating point types are frequently inexact (at least common IEEE formats are) and hence scaling the input will introduce artificial fractional digits. I have not taken much effort to do proper rounding, so some numbers will reverse into strange things (e.g. 123.0 could reverse into 992.1 instead of 321.0 (untested for this input, try some yourself))
the implementation is laughably template-happy. Think of it as the instructional part of this playful answer.
Oh, uncomment the DEBUGTRACE definition to ... get debug tracing :)
See it live here [click]TM
#include <cmath>
#include <limits>
#include <iostream>
#define MAX_DECIMAL_FRACTION 5
#define DEBUGTRACE(x) // do { std::cerr << x; } while (false)
template <typename T, bool is_integer> struct reverse_impl;
template <typename T>
struct reverse_impl<T, true>
{
static T reverse(T input)
{
T output;
for (output = 0; input; input/=10)
output = (output * 10) + input % 10;
return output;
}
};
template <typename T>
struct reverse_impl<T, false>
{
static T reverse(T input)
{
if (std::abs(input) <= std::numeric_limits<T>::epsilon())
return T(0);
// scale input
int log10 = (int) (std::log(input)/std::log(T(10)));
input *= std::pow(10, MAX_DECIMAL_FRACTION);
input = std::floor(input);
input /= std::pow(10, log10+MAX_DECIMAL_FRACTION);
DEBUGTRACE("debug: scaled " << input << " digits: ");
int iteration = std::max(log10+MAX_DECIMAL_FRACTION, MAX_DECIMAL_FRACTION);
if (std::floor(input) < 1)
{
input *= 10;
iteration--;
}
T output;
for (output = T(0);
iteration-- && std::floor(input) >= 1;
input-=std::floor(input), input*=T(10))
{
output = (output / T(10)) + std::floor(input);
DEBUGTRACE(std::floor(input));
}
DEBUGTRACE(std::endl);
return output * std::pow(10, log10);
}
};
template <typename T>
T reverse(T input)
{
return reverse_impl<T, std::numeric_limits<T>::is_integer>::reverse(input);
}
int main()
{
std::cout << reverse(-123l) << std::endl;
std::cout << reverse(123ul) << std::endl;
std::cout << reverse(123456.0) << std::endl;
std::cout << reverse(0.027f) << std::endl;
return 0;
}
***//here is the simple solution to find reverse of a function***
#include<iostream.h>
#include<conio.h>
void main()
{
int n,a,c,d,b;
clrscr();
cout<<"enter five integers";
cin>>n;
a=n/10000;
n=n%10000;
b=n/1000;
n=n%1000;
c=n/100;
n=n%100;
d=n/10;
n=n%10;
cout<<"number in reverse order is"<<n<<d<<c<<b<<a;
getch();
}
How do I raise a number to a power?
2^1
2^2
2^3
etc...
pow() in the cmath library. More info here.
Don't forget to put #include<cmath> at the top of the file.
std::pow in the <cmath> header has these overloads:
pow(float, float);
pow(float, int);
pow(double, double); // taken over from C
pow(double, int);
pow(long double, long double);
pow(long double, int);
Now you can't just do
pow(2, N)
with N being an int, because it doesn't know which of float, double, or long double version it should take, and you would get an ambiguity error. All three would need a conversion from int to floating point, and all three are equally costly!
Therefore, be sure to have the first argument typed so it matches one of those three perfectly. I usually use double
pow(2.0, N)
Some lawyer crap from me again. I've often fallen in this pitfall myself, so I'm going to warn you about it.
In C++ the "^" operator is a bitwise XOR. It does not work for raising to a power. The x << n is a left shift of the binary number which is the same as multiplying x by 2 n number of times and that can only be used when raising 2 to a power, and not other integers. The POW function is a math function that will work generically.
You should be able to use normal C methods in math.
#include <cmath>
pow(2,3)
if you're on a unix-like system, man cmath
Is that what you're asking?
Sujal
Use the pow(x,y) function: See Here
Just include math.h and you're all set.
While pow( base, exp ) is a great suggestion, be aware that it typically works in floating-point.
This may or may not be what you want: on some systems a simple loop multiplying on an accumulator will be faster for integer types.
And for square specifically, you might as well just multiply the numbers together yourself, floating-point or integer; it's not really a decrease in readability (IMHO) and you avoid the performance overhead of a function call.
I don't have enough reputation to comment, but if you like working with QT, they have their own version.
#include <QtCore/qmath.h>
qPow(x, y); // returns x raised to the y power.
Or if you aren't using QT, cmath has basically the same thing.
#include <cmath>
double x = 5, y = 7; //As an example, 5 ^ 7 = 78125
pow(x, y); //Should return this: 78125
if you want to deal with base_2 only then i recommend using left shift operator << instead of math library.
sample code :
int exp = 16;
for(int base_2 = 1; base_2 < (1 << exp); (base_2 <<= 1)){
std::cout << base_2 << std::endl;
}
sample output :
1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768
It's pow or powf in <math.h>
There is no special infix operator like in Visual Basic or Python
#include <iostream>
#include <conio.h>
using namespace std;
double raiseToPow(double ,int) //raiseToPow variable of type double which takes arguments (double, int)
void main()
{
double x; //initializing the variable x and i
int i;
cout<<"please enter the number";
cin>>x;
cout<<"plese enter the integer power that you want this number raised to";
cin>>i;
cout<<x<<"raise to power"<<i<<"is equal to"<<raiseToPow(x,i);
}
//definition of the function raiseToPower
double raiseToPow(double x, int power)
{
double result;
int i;
result =1.0;
for (i=1, i<=power;i++)
{
result = result*x;
}
return(result);
}
Many answers have suggested pow() or similar alternatives or their own implementations. However, given the examples (2^1, 2^2 and 2^3) in your question, I would guess whether you only need to raise 2 to an integer power. If this is the case, I would suggest you to use 1 << n for 2^n.
pow(2.0,1.0)
pow(2.0,2.0)
pow(2.0,3.0)
Your original question title is misleading. To just square, use 2*2.
First add #include <cmath> then
you can use pow methode in your code for example :
pow(3.5, 3);
Which 3.5 is base and 3 is exp
Note that the use of pow(x,y) is less efficient than x*x*x y times as shown and answered here https://stackoverflow.com/a/2940800/319728.
So if you're going for efficiency use x*x*x.
I am using the library cmath or math.h in order to make use of the pow() library functions that takes care of the powers
#include<iostream>
#include<cmath>
int main()
{
double number,power, result;
cout<<"\nEnter the number to raise to power: ";
cin>>number;
cout<<"\nEnter the power to raise to: ";
cin>>power;
result = pow(number,power);
cout<<"\n"<< number <<"^"<< power<<" = "<< result;
return 0;
}
use pow() function in cmath, tgmath or math.h library.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int a,b;
cin >> a >> b;
cout << pow(a,b) << endl; // this calculates a^b
return 0;
}
do note that if you give input to power as any data type other than long double then the answer will be promoted to that of double. that is it will take input and give output as double. for long double inputs the return type is long double. for changing the answer to int use,
int c=(int)pow(a,b)
But, do keep in mind for some numbers this may result in a number less than the correct answer. so for example you have to calculate 5^2, then the answer can be returned as 24.99999999999 on some compilers. on changing the data type to int the answer will be 24 rather than 25 the correct answer. So, do this
int c=(int)(pow(a,b)+0.5)
Now, your answer will be correct.
also, for very large numbers data is lost in changing data type double to long long int.
for example you write
long long int c=(long long int)(pow(a,b)+0.5);
and give input a=3 and b=38
then the result will come out to be 1350851717672992000 while the correct answer is 1350851717672992089, this happens because pow() function return 1.35085e+18 which gets promoted to int as 1350851717672992000. I suggest writing a custom power function for such scenarios, like:-
long long int __pow (long long int a, long long int b)
{
long long int q=1;
for (long long int i=0;i<=b-1;i++)
{
q=q*a;
}
return q;
}
and then calling it whenever you want like,
int main()
{
long long int a,b;
cin >> a >> b;
long long int c=__pow(a,b);
cout << c << endl;
return 0;
}
For numbers greater than the range of long long int, either use boost library or strings.
int power (int i, int ow) // works only for ow >= 1
{ // but does not require <cmath> library!=)
if (ow > 1)
{
i = i * power (i, ow - 1);
}
return i;
}
cout << power(6,7); //you can enter variables here