C++ digit sum programm while loop [duplicate] - c++

This question already has answers here:
cin >> fails with bigger numbers but works with smaller ones?
(4 answers)
Closed 5 years ago.
I have recently made a program in C++ that counts a sum of digits in an input number (code below). The program works this way. A user is asked to input a natural number x. Then the program is put into a while loop which is meant to proceed until the x reaches 0. The y is a simple equation which determines the last digit of a number (i.e. x=123, y=3). D_sum is the sum of digits in x (i.e. x=123, d_sum=3).
The x=(x-y)/10 is used to help to calculate next digit (i.e. x=(123-3)/10=120/10=12). The program works fine until you input a number with more than 10 digits (screen below).
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int x,y;
int d_sum = 0;
cout << "x= ";
cin >> x;
while(x > 0)
{
y=x % 10;
d_sum++;
x = (x - y) / 10;
}
cout << d_sum << endl;
system("pause");
return 0;
}
Screen:

Take a look at http://en.cppreference.com/w/cpp/language/types
, looks like on your platform int is 32 bits. e.g. if int is 32 bit, maximum number it may be able to store would 2^31 = 2147483648.

Related

How do I find 20 odd numbers starting from a number entered by user? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
So, i was given an assignment to find 20 odd numbers starting from a number entered by user.. I know how to find odd numbers. but I don't know how to find them starting from a number entered by user.
I tried this:
#include<iostream>
using namespace std;
int main(){
int num,i;
cout<<"Enter num: ";
cin>>num;
for(i=num;i<=20;i++){
if(i%2!=0)
cout<<num <<endl;
}
}
but it outputs the number entered by user 20 times.
As the comment says, you output the num, not newly calculated i, but even if you fix that, you will output only few odd numbers (or none), for example for input 50 there will be no output instead of odd 20 numbers (because 50 <= 20 is always false, so no for body will be executed). Plus you are doing lot of math... while the whole task can collapse to trivial:
#include<iostream>
int main() {
int num;
std::cout << "Enter num: ";
std::cin >> num;
num |= 1; // turn user number into odd one (if it was even)
const int endNum = num + 20*2; // calculate the first odd number after 20 of them (end value)
while (num < endNum) {
std::cout << num << std::endl;
num += 2;
}
}
doing just simple addition +2 in loop.
edit: btw, why num |= 1; guarantees odd number... because integers in computer are stored as binary values, where every digit is different power of two, with the least significant bit corresponding to the zeroth power of two (i.e. value 1). If this bit is set, then the value is odd, because dividing by two does apply from first power of two upward and this bottom bit is remainder. And if it is reset, the value is even, for the same reason, the bottom bit is remainder after you would divide the value by two. The binary or operator |= 1 will set the least significant bit to one, turning any integer value to odd one.
This is the special case, when your task involves calculation based on powers of two. Because all the values in computer are already encoded in the binary way, there are usually shortcuts how to get the result of such calculation. Like for example to get remainder of division by 16 from integer n you can do binary and: n & 15 and you have the remainder. Or to divide by 16 you can shift the unsigned integer value by four bits to the right like n >> 4 to get the result. But this doesn't work with calculations which are not power-of-two based, i.e. remainder after dividing by ten is NOT n & 9, because 9 is 0b1001, so different values will be trimmed down to only values 0, 1, 8 or 9, but remainders after dividing by 10 can be any value from 0 to 9. .. while 15 is in binary 0b1111, so such binary and-mask will produce all values from 0 to 15, and they correspond to the remainder by div 16.
The bug in your code is that you print num instead of i. So just do:
cout<< i <<endl;
^
But you can simplify your code a lot by doing:
#include<iostream>
using namespace std;
int main(){
int num,i;
cout<<"Enter num: ";
cin>>num;
if (num%2 == 0) ++num; // Make sure num is odd
for(i=0; i < 20; ++i){ // Print 20 numbers
cout << (num + 2*i) << endl; // Multiply i by 2 and add it to num
// so that the result is the next odd number
}
}
note
As suggested by Ped7g the line
if (num%2 == 0) ++num; // Make sure num is odd
can be made more simple. Just replace it with
num |= 1; // Set the least significant bit so that num is odd
This loop
for(i=num;i<=20;i++){
if(i%2!=0)
cout<<num <<endl;
}
does not make sense because it checks the variable i instead of the variable num whether it is an odd number. And it is obvious there will be outputted a half of 20 values of i.
The program can look the following way
#include <iostream>
int main()
{
const size_t N = 20;
int n = 0;
std::cout << "Enter a number: ";
std::cin >> n;
n |= 1; // make the first odd number
for ( size_t i = 0; i < N; i++ )
{
std::cout << n << ' ';
n += 2;
}
}
Its output might look the following way
Enter a number: 10
11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49
A more correct professional code can look the following way
#include <iostream>
#include <limits>
int main()
{
const size_t N = 20;
int n = 0;
std::cout << "Enter a number: ";
std::cin >> n;
n |= 1;
for ( size_t i = 0; i < N; i++ )
{
std::cout << n << ' ';
n = std::numeric_limits<int>::max() - 2 < n ? std::numeric_limits<int>::min() | 1 : n + 2;
}
}
In this case if the user will enter the maximum integer value then the output will look like
Enter a number: 2147483647
2147483647 -2147483647 -2147483645 -2147483643 -2147483641 -2147483639 -2147483637 -2147483635 -2147483633 -2147483631 -2147483629 -2147483627 -2147483625 -2147483623 -2147483621 -2147483619 -2147483617 -2147483615 -2147483613 -2147483611

I am trying to do basic addition in c++ but large numbers are showing [duplicate]

This question already has an answer here:
I am trying to write a simple calculation program but the answer keeps coming back as 0
(1 answer)
Closed 6 years ago.
I am tryimg to do basic addition in c++ but a large number shows instead of the number thats suposed to show.
#include <iostream>
using namespace std;
int main()
{
int x;
int y;
int sub = x + y;
cout<<"Enter First number:"<<endl;
cin>>x;
cout<<"Enter second number:"<<endl;
cin>>y;
cout << "The sum is: "<< sub << endl;
return 0;
}
When I run this it shows the sum as "6996596".
sub is being created and attributed before x and y are set. When you declare the variables but don't initialize then, you get unknown values from what you had previously on the stack.
If you move the sub variable attribution to after x and y were read from the terminal, the program would work correctly.
You are computing your sum before accepting user input. Furthermore, you are summing two uninitialized variables, leading to undefined behavior.

Can't get math c++ program to work [duplicate]

This question already has answers here:
Why does division result in zero instead of a decimal?
(5 answers)
Closed 8 years ago.
So i am trying to make one of my first very simple math programs in c++. the problem is that
i can't seem to get the function potodds to do what i want. There is no problem in getting it to multiple the two variables (x,y) that works perfectly fine. the problem occurs when i try to replace return x*y*100 with return (x/y)*100. in this case it always return the value 0?
Hopes that someone out there can help me pinpoint my mistake.
The code looks like this:
#include "stdafx.h"
#include <iostream>
int x;
int y;
int potodds(int x, int y) {
return x * y * 100; //(x/y)*100;
}
int main() {
using namespace std;
cout << "what's the size of the pot?" << endl;
cin >> y;
cout << "what's the size of the bet?" << endl;
cin >> x;
cout << "your potodds are:" << endl;
cout << potodds(x, y) << endl;
return 0;
}
Thanks to Ebyrob i got the solution.
the problem that I was having was that I was trying to divide an integer, that was assigned a decimal value and by definition an integer can only contain whole numbers. The result was that the integer was rounded down to zero.
x and y are defined as integral values. The integral division returns only the quotient. So if x is less than y then x /y will be equal to 0.
So it would be better to substitute expression ( x /y ) * 100 for ( 100 * x ) / y
Otherwise use float numbers
For example
( double )x / y * 100
Changing int to double should solve the problem but also "using namespace std;" is always outside of main when I program. I don't know if this affects anything but you might consider putting it above your main function because it might be causing a problem now or it might cause a problem in another program you make. I think it is a matter of it being global or private but I would have it outside of main so that any other functions you use can use it ( assuming I'm right ).
If you divide two integers, the result will be an integer (the quotient: the remainder is discarded).
So, 1 / 2 -> 0 instead of 0.5.
Note also that (1 / 2) * 100 is therefore 0 * 100 -> 0, while, as Vlad says,
100*1/2 -> 100/2 -> 50, which is what you want.

What is wrong with this solution of mine for the PKU Judge ID 1003? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
Here is the link to the Problem ID 1003 of the PKU Judge: http://poj.org/problem?id=1003
All we need to do for this problem is to calculate the sum of a Harmonic Progression and Compare it with the variable we have already inputted
I am getting right answers for the sample input cases, but I don't know why my answer is not getting accepted? I am getting 'Wrong Answer' as the Result.
The was a part in the problem that says "The input consists of one or more test cases, followed by a line containing the number 0.00 that signals the end of the input" I don't know how to do that 0.00 part, I am just taking single input, I didn't understand how to do that?
Here is my solution:
#include<iostream>
using namespace std;
int main()
{
float c;
float sum = 0;
cin >> c;
short int i = 1;
while(1)
{
sum += (float)1/(i+1);
if(sum >= c)
{
cout << i << " card(s)";
break;
}
i++;
}
return 0;
}
The input consists of one or more test cases, followed by a line containing the number 0.00 that signals the end of the input. Each test case is a single line containing a positive floating-point number c whose value is at least 0.01 and at most 5.20; c will contain exactly three digits.
Your program won't take correct input.
The input consists of one or more test cases.
Use the exact output format shown in the examples, which means you should print a line break after each case.
I made a little changes to your code to get it accepted.
#include <iostream>
using namespace std;
int main() {
float c;
while (true) {
cin >> c;
if (c == 0.0)
return 0;
float sum = 0;
short int i = 1;
while (1) {
sum += 1.0 / (i + 1);
if (sum >= c) {
cout << i << " card(s)" << endl;
break;
}
i++;
}
}
}

Why this Factorial function returning zero for large numbers [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Calculating factorial of large numbers in C
Firstly, I am new to C++. I have tried below program to calculate factorial of any number.
#include <iostream>
using namespace std;
unsigned long factorial(unsigned long n){
return n <= 1 ? 1 : n * factorial(n-1);
}
int main()
{
cout << "Enter any Number to calculate factorial." <<endl;
unsigned long n;
cin >> n ;
cout << factorial(n) ;
}
If i give small numbers like 5,3,20 it returns me exact value. But if I give numbers like 34 etc.. It is returning me zero. I assume that it is exceeding the limit range. Please help me on this to return exact result whatever the number I enter.
Factorials are huge.
34! = 295232799039604140847618609643520000000
This barely fits into 128 bits. If your compiler supports a 128-bit number type, you can use it to calculate factorials up to 34. If not, or if you need anything larger, you will need to use some kind of bignum library.