Issue with base converter function [duplicate] - c++

This question already has answers here:
Strange behaviour of the pow function
(5 answers)
Closed 6 years ago.
I'm helping a friend with a C++ assignment. There is an issue with the folowing base converter function:
#include <iostream>
#include <cmath>
using namespace std;
int strToInt(string num, unsigned base){
int result = 0;
for (int i=0; i<num.length(); i++) {
if (num[i]>='0' && num[i]<='9')
result += (num[i]-'0')*pow(base,num.length()-i-1);
else if (num[i]>='A' && num[i]<='F')
result += (num[i]-'A'+10)*pow(base,num.length()-i-1);
else if (num[i]>='a' && num[i]<='f')
result += (num[i]-'a'+10)*pow(base,num.length()-i-1);
}
return result;
}
int main()
{
string number;
int base;
while(number.compare("exit")!=0){
cin>>number;
cin>>base;
cout<<strToInt(number,base)<<"\n\n";
}
return 0;
}
For some inexplicable reason every time I enter 3 and 5 digit decimals and chose base 10 I am getting the proper number -1.
E.g.
100
10
99
10000
10
9999
I've been going over this function for the last 5-6 hours and adding all types of debug code, but for the good of me I can't figure out what the hell is wrong.
Code style remarks are also very appreciated.
Cheers

std::pow does floating-point math. You're probably getting a round-off error somewhere. The usual way to accumulate values is to multiply and add each time through the loop:
result *= base;
result += ch - '0';

Related

Sum of N reciprocals[Division mistake] [duplicate]

This question already has an answer here:
Integer division always zero [duplicate]
(1 answer)
Closed 7 years ago.
#include <iostream>
#include <math.h>
#include <ctype.h>
using namespace std;
int main()
{
int n=0,tot=0;
float sum = 0;
float average = 0;
float product = 1;
cout<<"Type an integer and press Enter:\n";
cin>>n;
/*
Your logic goes here
*/
for(int i=1;i<=n;i++){
cout<<sum<<endl;
sum= sum+(1/i);
product=product*1/i;
tot++;
}
cout<<"Sum, product and average of reciprocals are:\n";
cout<<sum<<endl;
cout<<product<<endl;
cout<<average<<sum/tot<<endl;
}
Anyone please tell me what I am doing wrong , my sum is always equal to one, i don't know why. I put cout and at each iteration it printout "1". My logic is right but there is some mistake which i can't find.
The following line
sum= sum+(1/i);
Does integer division, when i = 1 it will evaluate to 1, otherwise when i > 1, it will be 0. I would use 1.0/i to force floating point division
EDIT: I would make the change to your product update as well
1/i will be 0 for all i greater than 1. Integer division. You will want to fix this by replacing 1/i with 1.0/i.
See ideone here

Template<> not working or for ints [duplicate]

This question already has answers here:
Why does division result in zero instead of a decimal?
(5 answers)
Closed 7 years ago.
Here is the code I am having trouble with it seems to work logically but perhaps I am missing a small detail as it doesn't work for chars or ints.
Whenever I run it I get weird output like all Fs or all As.
#include <iostream>
template<class T>
char gradeIt(T mark,T maxMark){
T grade =(mark/maxMark)*100;
if(grade > 79)
return 'A';
else if(grade<=79 && grade >= 69) {
return 'B';
}
else if(grade<=69 && grade>59)
return 'C';
else if(grade>50 && grade <=59)
return 'D';
else
return 'F';
}
template<>
char gradeIt<char>(char mark,char maxMark){
return mark;
}
T grade =(mark/maxMark)*100;
When the template parameter T is int this is performing integer division. For example, 80 / 100 = 0.
You could instead do.
T grade = mark * 100 / maxMark;
It looks like
(mark/maxMark)*100
is performing integer division, which will round to 0 every time.
You should static_cast<double>(mark)/maxMark to first convert to floating point so you don't lose any digits after the decimal place.
This isn't doing what you want for integers.
T grade =(mark/maxMark)*100;
In the case of integer division (int and char have the same behavior in this) maxMark is greater than mark then the result will just be 0.
For example
int x = 100;
int y = 5;
int z = y/x;
assert(z==0);

Segmentation fault in iterative summation [duplicate]

This question already has answers here:
How does the scanf function work in C?
(7 answers)
Closed 8 years ago.
Write a program to read an integer number and keep on adding the digits till
we get a number with a single digit. For example, 7976 yields an output of 2
(7976 - - t 29 - - t 11 - - t 2).
For this, your main() function must call the function sumdigits(0) to solve
the problem, and then print the final result.
I have solved this problem and the logic is correct, I am not getting any output When i give my input it just move to next line.
#include <stdio.h>
sumdigits(int x)
{
int n = x;
int y = 0;
while(n>0) {
y = y + n % 10;
n = n / 10;
}
return y;
}
int main(void)
{
int a;
scanf("%d",&a);
while(a>10) {
a=sumdigits(a);
}
printf("%d",a);
}
Problem is with this line
scanf("%d",a);
It should be
scanf("%d", &a);
//----------^ use &

Sum of prime numbers less than 2 million [duplicate]

This question already has answers here:
Sum of all primes under 2 million
(5 answers)
Closed 9 years ago.
I am trying to solve a Project Euler problem, it wants me to find the sum of prime numbers below 2 million. Here is the code I wrote :
#include <iostream>
using namespace std;
bool isPrime (int x)
{
for(int i = 2; i < x; i++)
{
if(x % i == 0)
return false;
}
return true;
}
int main ()
{
int x = 0;
for(int i = 3 ; i < 2000000;i++)
{
if(isPrime(i))
x = x + i;
}
cout<<x+2<<endl;
}
I know this is not an efficient way to solve this problem. I found an easier way but I think this solution should give the correct answer too. The answer this code finds is : 1179908154. Can you tell me why this code is giving the wrong answer?
The code gives you the wrong answer since you reach to the point x, which is of type int cant represent your number.
You can use another data type unsigned long long ? which will be able to hold it without overflowing

c++ getting TwoRandomNumbers, min and max [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
C++ Random number homework question
Guys, I need help (yes, last minute homework help). I'm suppose to write a function named getTwoRandomNumbers that uses two parameters to return two different random numbers. The function is suppose to accept two parameters that specify the minimum and maximum values of the random number.
I need to write data validation code that ensures that two identical random numbers will never be returned. This is what I have so far: (ANY DIRECTION IS GREATLY APPRECIATED)
Ok, I made changes and now have this:
#include <iostream>
#include <iomanip>
#include <cmath>
#include <time.h>
using namespace std;
float getTwoRandomNumbers (int Min, int Max, int & number1, int & number2);
void main()
{
cout << "The two random numbers are " << getTwoRandomNumbers << endl;
}
float getTwoRandomNumbers (int Min, int Max, int & number1, int & number2)
{
int loopNumber, number;
for (loopNumber = 0; loopNumber <= 200 ; loopNumber ++)
{
number = rand();
if (loopNumber < 100 && number >= Min && number <= Max)
{
number1 = number;
}
if (loopNumber > 100 && number >= Min && number <= Max)
{
number2 = number;
}
return number2;
}
}
First off, you're on the right path with passing back both values through the parameters of the function. Then it seems like you're also trying to get the 2nd value back through the function return.
Since you need to get more than 1 value from the function, ignore the return value and just use the 2 parameters passed to get your return values.
Also, try thinking out the question in your head, what are you trying to do? Get 2 random values while number1 is not equal to number2
That should give you a decent start on the logic flow for getting the random numbers to pass back.
One thing for you: As I reformatted your code, it became apparent that you have a return within your for loop. That means getTwoRandomNumbers will always return after the first iteration. I'm 99.99% positive this is not what you have in mind.