Ok, well, I'm writing a program for a store (just a project to learn c++) and I'm having a problem. The white loop doesn't seem to do what it's supposed to, the program just goes through it.
I have a function:
int decimali_float (pole &artikli){
int num = artikli.cena;
int count = 0;
num = abs(num);
num = num - (int)num;
while(num >= 0.0000001){
num *= 10;
count++;
num -= (int)num;
}
return count;
}
And my struct is this :
struct pole{
int sifra;
string opis;
float cena;
int vlez_kol;
int izlez_kol;
float dan_stapka;
float iznos;
int datum;
};
And I've got an array declared for the struct:
pole artikli[100];
And here's my code where the while loop gets skipped.
for (int i = 0; i < 5; i++){
while(!(cin >> artikli[i].cena) || decimali_float(artikli[i]) > 2){
cout << "Error, try again." << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
Where is my mistake?
decimali_float is a function to count the decimals of a number.
the element cena of the struct means price in English.
pole artikli[100] is the amount of elements(articles) in the struct
Is it only me, or num is an integer value which is explicitly set to value equal or below 0:
int num = artikli.cena;
num = abs(num);
num = num - (int)num;
Obviously it will always be less than whatever non-zero constant it is compared too and the while loop will get skipped.
Update
It appears that the main question was already addressed in comments. As for the follow-up question, instead of counting decimal places one may simply check, whether there is a residue from subtracting an adjusted "cena" from the original one (assuming cena is positive for now):
double cena1 = cena * 100;
if ((cena1 - floor(cena1)) > 0.000001)
// error condition here
Related
#include<iostream>
using namespace std;
int main(){
int i = 1;
int sum;
int N;
cout << "Enter a number N: ";
cin >> N;
while(i<=N)
{
if(i%2 == 0)
{
sum = sum + i;
}
else
{
i = i + 1;
}
}
cout << sum;
}
This is to print the sum of all even numbers till 1 to N.
As I try to run the code, I am being asked the value of N but nothing is being printed ahead.
For starters the variable sum is not initialized.
Secondly you need to increase the variable i also when it is an even number. So the loop should look at least like
while(i<=N)
{
if(i%2 == 0)
{
sum = sum + i;
}
i = i + 1;
}
In general it is always better to declare variables in minimum scopes where they are used.
So instead of the while loop it is better to use a for loop as for example
for ( int i = 1; i++ < N; ++i )
{
if ( i % 2 == 0 ) sum += i;
}
while(i<=N)
{
if(i%2 == 0)
{
sum = sum + i;
}
else
{
i = i + 1;
}
}
Let's step through this. Imagine we're on the loop where i = 2 and you've entered N = 5. In that case...
while(i <= N)
2 <= 5 is true, so we loop
if(i%2 == 0)
2 % 2 == 0 is true, so we enter this branch
sum = sum + i;
Update sum, then head back to the top of the loop
while(i <= N)
Neither i nor N have changed, so 2 <= 5 is still true. We still loop
if(i%2 == 0)
2 % 2 == 0 is still true, so we enter this branch again...
Do you see what's happening here? Since neither i nor N are updated, you'll continue entering the same branch and looping indefinitely. Can you think of a way to prevent this? What would need to change?
Also note that int sum; means that sum will have a garbage value (it's uninitialized). If you want it to start at 0, you'll need to change that to
int sum = 0;
You're looping infinitly when i is even because you don't increase it.
Better option would be this if you want to use that while loop :
while(i<=N)
{
if(i%2 == 0)
sum = sum + i;
i=i+1;
}
cout << sum;
If you don't need to do anything when the condition is false, just don't use an else.
No loops are necessary and sum can be evaluated at compile time if needed too
// use unsigned, the whole excercise is pointless for negative numbers
// use const parameter, is not intended to be changed
// constexpr is not needed, but allows for compile time evaluation (constexpr all the things)
// return type can be automatically deduced
constexpr auto sum_of_even_numbers_smaller_then(const unsigned int n)
{
unsigned int m = (n / 2);
return m * (m + 1);
}
int main()
{
// compile time checking of the function
static_assert(sum_of_even_numbers_smaller_then(0) == 0);
static_assert(sum_of_even_numbers_smaller_then(1) == 0);
static_assert(sum_of_even_numbers_smaller_then(2) == 2);
static_assert(sum_of_even_numbers_smaller_then(3) == 2);
static_assert(sum_of_even_numbers_smaller_then(7) == 12);
static_assert(sum_of_even_numbers_smaller_then(8) == 20);
return 0;
}
int main(){
int input; //stores the user entered number
int sum=0; //stroes the sum of all even numbers
repeat:
cout<<"Please enter any integer bigger than one: ";
cin>>input;
if(input<1) //this check the number to be bigger than one means must be positive integer.
goto repeat; // if the user enter the number less than one it is repeating the entry.
for(int i=input; i>0; i--){ // find all even number from your number till one and than totals it.
if(i%2==0){
sum=sum+i;
int j=0;
j=j+1;
cout<<"Number is: "<<i<<endl;
}
}
cout<<endl<<"The sum of all even numbers is: "<<sum<<endl;}
Copy this C++ code and run it, it will solve your problem.
There are 2 problems with your program.
Mistake 1
The variable sum has not been initialized. This means that it has(holds) an indeterminate value. And using this uninitialized variable like you did when you wrote sum = sum + i; is undefined behavior.
Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely on the output of a program that has undefined behavior.
This is why it is advised that:
always initialize built in types in local/block scope.
Mistake 2
The second problem is that you're not updating the value of variable i.
Solution
You can solve these problems as shown below:
int main(){
int i = 1;
int sum = 0; //INITIALIZE variable sum to 0
int N;
cout << "Enter a number N: ";
cin >> N;
while(i<=N)
{
if(i%2 == 0)
{
sum = sum + i;
}
i = i + 1; //update(increase i)
}
cout << sum;
}
1For more reading(technical definition of) on undefined behavior you can refer to undefined behavior's documentation which mentions that: there are no restrictions on the behavior of the program.
According to my lecturer a balanced number is balanced if the sum of its divisors is equal to it self. for example: 6 is a balanced number because 1+2+3=6
These are my very first homework so i am struggeling.
#include <iostream>
using namespace std;
int main() {
int num = 0;
int sum = 0;
cout << "Enter a number" << endl;
cin >> num;
if (num % (num-1) == 0 ){
for(int i =1; sum == 0; i++) {
sum += (num - i);
}
if (sum == num) {
cout << "Great Success" << endl;
}
else {
cout << "Wrong number" << endl;
}
}
}
Do the maths first. Often code being a bit messy is just a consequence of not preparing yourself good enough to write the code. Dont start writing code before you know what you want to write. Frankly, from your code one can see that it is something related to num-1 dividing num, but otherwise it is not clear how it is supposed to solve the problem. And its intendation makes it quite hard to read, so lets forget about the code and start from scratch...
y is a divisor of x exactly if x % y == 0. The biggest possible divisor of x is x/2. To get all divisors we can simply check every number from 2 up to x/2 (1 is always considered a divisor, hence no need to check).
Only now we can write some code:
int x;
std::cin >> x;
int sum = 1;
for (int y = 2; y <= x/2; ++y){
if ( check_if_y_is_divisor) { sum += y; }
}
bool is_balanced = sum == x;
I left a tiny hole in the code that you have to fill (I just dont like to give away the full solution when it is homework).
I am new to functions and i am really trying to understand how they work, my teacher gave us a problem where by we were to pass a number to a function between the range of 1-12 and the function was then meant to do the times tales of that number so I asked the user to enter a number and if the number is less then 1 and greater then 12 exit, else pass the number to the function and then I used a for loop to do the multiplication for me (as far as I am aware) but nothing seems to happen? Νo doubt I am doing something really stupid, any help is much appreciated.
#include <iostream>
using namespace std;
int TimesTables (int num);
int main(int argc, const char * argv[]) {
int number;
cout << "enter a number to multiply by, with a range of 1-12: ";
cin >> number;
if (number < 1 && number > 12)
return EXIT_FAILURE;
else {
int tables = TimesTables(number);
cout << tables;
}
return 0;
}
int TimesTables (int num) {
for ( int i = 0; num <=12; i ++)
num = num * i;
return num;
}
Running i from 0 is going to set num to 0, and therefore any multiplication after that.
Your loop is also rather dubious. Why are you checking num <= 12 rather than i <= 12?
Shouldn't your loop take the form
for ( int i = 1; i <=12; i ++){
// Print num * i
cout << num * i;
}
// There's no need to return anything back to the caller
for ( int i = 0; num <=12; i ++)
num = num * i;
Here i starts from 0, so any multiplication you do afterwards doesn't affect the result (num). Moreover, you want to go from 1 to 12, so you should start from 0 and finish at 12 - 1, or start from 1 and finish at 12.
So change this:
for ( int i = 0; num <=12; i ++)
to this:
for ( int i = 1; i <=12; i ++)
since you want to stop when i reaches 12, not num, i is the counter of the for-loop!
I am writing code to get the last digit of very large fibonacci numbers such as fib(239), etc.. I am using strings to store the numbers, grabbing the individual chars from end to beginning and then converting them to int and than storing the values back into another string. I have not been able to test what I have written because my program keeps abruptly closing after the std::cin >> n; line.
Here is what I have so far.
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using namespace std;
char get_fibonacci_last_digit_naive(int n) {
cout << "in func";
if (n <= 1)
return (char)n;
string previous= "0";
string current= "1";
for (int i = 0; i < n - 1; ++i) {
//long long tmp_previous = previous;
string tmp_previous= previous;
previous = current;
//current = tmp_previous + current; // could also use previous instead of current
// for with the current length of the longest of the two strings
//iterates from the end of the string to the front
for (int j=current.length(); j>=0; --j) {
// grab consectutive positions in the strings & convert them to integers
int t;
if (tmp_previous.at(j) == '\0')
// tmp_previous is empty use 0 instead
t=0;
else
t = stoi((string&)(tmp_previous.at(j)));
int c = stoi((string&)(current.at(j)));
// add the integers together
int valueAtJ= t+c;
// store the value into the equivalent position in current
current.at(j) = (char)(valueAtJ);
}
cout << current << ":current value";
}
return current[current.length()-1];
}
int main() {
int n;
std::cin >> n;
//char& c = get_fibonacci_last_digit_naive(n); // reference to a local variable returned WARNING
// http://stackoverflow.com/questions/4643713/c-returning-reference-to-local-variable
cout << "before call";
char c = get_fibonacci_last_digit_naive(n);
std::cout << c << '\n';
return 0;
}
The output is consistently the same. No matter what I enter for n, the output is always the same. This is the line I used to run the code and its output.
$ g++ -pipe -O2 -std=c++14 fibonacci_last_digit.cpp -lm
$ ./a.exe
10
There is a newline after the 10 and the 10 is what I input for n.
I appreciate any help. And happy holidays!
I'm posting this because your understanding of the problem seems to be taking a backseat to the choice of solution you're attempting to deploy. This is an example of an XY Problem, a problem where the choice of solution method and problems or roadblocks with its implementation obfuscates the actual problem you're trying to solve.
You are trying to calculate the final digit of the Nth Fibonacci number, where N could be gregarious. The basic understanding of the fibonacci sequence tells you that
fib(0) = 0
fib(1) = 1
fib(n) = fib(n-1) + fib(n-2), for all n larger than 1.
The iterative solution to solving fib(N) for its value would be:
unsigned fib(unsigned n)
{
if (n <= 1)
return n;
unsigned previous = 0;
unsigned current = 1;
for (int i=1; i<n; ++i)
{
unsigned value = previous + current;
previous = current;
current = value;
}
return current;
}
which is all well and good, but will obviously overflow once N causes an overflow of the storage capabilities of our chosen data type (in the above case, unsigned on most 32bit platforms will overflow after a mere 47 iterations).
But we don't need the actual fib values for each iteration. We only need the last digit of each iteration. Well, the base-10 last-digit is easy enough to get from any unsigned value. For our example, simply replace this:
current = value;
with this:
current = value % 10;
giving us a near-identical algorithm, but one that only "remembers" the last digit on each iteration:
unsigned fib_last_digit(unsigned n)
{
if (n <= 1)
return n;
unsigned previous = 0;
unsigned current = 1;
for (int i=1; i<n; ++i)
{
unsigned value = previous + current;
previous = current;
current = value % 10; // HERE
}
return current;
}
Now current always holds the single last digit of the prior sum, whether that prior sum exceeded 10 or not really isn't relevant to us. Once we have that the next iteration can use it to calculate the sum of two single positive digits, which cannot exceed 18, and again, we only need the last digit from that for the next iteration, etc.. This continues until we iterate however many times requested, and when finished, the final answer will present itself.
Validation
We know the first 20 or so fibonacci numbers look like this, run through fib:
0:0
1:1
2:1
3:2
4:3
5:5
6:8
7:13
8:21
9:34
10:55
11:89
12:144
13:233
14:377
15:610
16:987
17:1597
18:2584
19:4181
20:6765
Here's what we get when we run the algorithm through fib_last_digit instead:
0:0
1:1
2:1
3:2
4:3
5:5
6:8
7:3
8:1
9:4
10:5
11:9
12:4
13:3
14:7
15:0
16:7
17:7
18:4
19:1
20:5
That should give you a budding sense of confidence this is likely the algorithm you seek, and you can forego the string manipulations entirely.
Running this code on a Mac I get:
libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: basic_string before callin funcAbort trap: 6
The most obvious problem with the code itself is in the following line:
for (int j=current.length(); j>=0; --j) {
Reasons:
If you are doing things like current.at(j), this will crash immediately. For example, the string "blah" has length 4, but there is no character at position 4.
The length of tmp_previous may be different from current. Calling tmp_previous.at(j) will crash when you go from 8 to 13 for example.
Additionally, as others have pointed out, if the the only thing you're interested in is the last digit, you do not need to go through the trouble of looping through every digit of every number. The trick here is to only remember the last digit of previous and current, so large numbers are never a problem and you don't have to do things like stoi.
As an alternative to a previous answer would be the string addition.
I tested it with the fibonacci number of 100000 and it works fine in just a few seconds. Working only with the last digit solves your problem for even larger numbers for sure. for all of you requiring the fibonacci number as well, here an algorithm:
std::string str_add(std::string a, std::string b)
{
// http://ideone.com/o7wLTt
size_t n = max(a.size(), b.size());
if (n > a.size()) {
a = string(n-a.size(), '0') + a;
}
if (n > b.size()) {
b = string(n-b.size(), '0') + b;
}
string result(n + 1, '0');
char carry = 0;
std::transform(a.rbegin(), a.rend(), b.rbegin(), result.rbegin(), [&carry](char x, char y)
{
char z = (x - '0') + (y - '0') + carry;
if (z > 9) {
carry = 1;
z -= 10;
} else {
carry = 0;
}
return z + '0';
});
result[0] = carry + '0';
n = result.find_first_not_of("0");
if (n != string::npos) {
result = result.substr(n);
}
return result;
}
std::string str_fib(size_t i)
{
std::string n1 = "0";
std::string n2 = "1";
for (size_t idx = 0; idx < i; ++idx) {
const std::string f = str_add(n1, n2);
n1 = n2;
n2 = f;
}
return n1;
}
int main() {
const size_t i = 100000;
const std::string f = str_fib(i);
if (!f.empty()) {
std::cout << "fibonacci of " << i << " = " << f << " | last digit: " << f[f.size() - 1] << std::endl;
}
std::cin.sync(); std::cin.get();
return 0;
}
Try it with first calculating the fibonacci number and then converting the int to a std::string using std::to_string(). in the following you can extract the last digit using the [] operator on the last index.
int fib(int i)
{
int number = 1;
if (i > 2) {
number = fib(i - 1) + fib(i - 2);
}
return number;
}
int main() {
const int i = 10;
const int f = fib(i);
const std::string s = std::to_string(f);
if (!s.empty()) {
std::cout << "fibonacci of " << i << " = " << f << " | last digit: " << s[s.size() - 1] << std::endl;
}
std::cin.sync(); std::cin.get();
return 0;
}
Avoid duplicates of the using keyword using.
Also consider switching from int to long or long long when your numbers get bigger. Since the fibonacci numbers are positive, also use unsigned.
The question:
Input data will give the number of test-cases in the first line.
Then test-cases themselves will follow, one case per line.
Each test-case describes an array of positive integers with value of 0 marking end. (this zero should not be included into calculations!!!).
Answer should contain average values for each array, rounded to nearest integer (see task on rounding), separated by spaces.
Problem:
Works fine but at third indice sum is assigned value of arrayInput and it messes everything up. Why does this happen and how can I fix it?
//araytest
#include<cmath>
#include<iostream>
using namespace std;
int main()
{
//var
int i = 0;
int array[13] = {};
//take in # arrays
cin >> i;
for(int x = 0; x<i; x++ )
{
//reset variables (for every array)
float arraySize = 0,
sum = 0, avg = 0;
int indice = 0,
arrayInput = 0;
while(cin >> arrayInput){
if(arrayInput == 0)
{
if(indice == 0)
{
arraySize = 1; /*if only 0 put in first indice
to prevent divide by 0 */
break;
}
else
{
arraySize = indice; // 0 doesn't count
break;
}
}
sum += arrayInput;
array[indice] = arrayInput;
arrayInput = 0;
indice++;
}
avg = round(sum/arraySize);
cout << avg << " ";
}
return 0;
}
First, like other people said, the array you used in this code is totally useless. It did nothing but save arrayinput.
Second, you let arraysize sum avg to be type float. However, arrayinput is assigned to be integer!! That means you never get result like this 2.xxx. So the type you declare for variables is meaningless. They should have same type declaration. I don't understand why you code does not work well. Because if you enter integer number, you wont get anything wrong. But it will crash if you give number like 2.xxx or x.xxx.