简体   繁体   中英

A C++ error that I don't understand

So this is my code

#include "stdafx.h"
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    int kol=0, x;

cout << "Insert a number: ";
cin >> x;

while (x > 0);
{
    div_t output;
    output = x;
    x = div(output, 10);
    kol += kol;
}
cout << "Amount: " << kol << endl;
system ("pause");
return 0;
}

And I got this error: Error 1 error C2679: binary '=' : no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversation)

Can someone tell me what I did wrong, and how to fix?

You are treating div_t like an int; it isn't one. It's a struct.

See http://en.cppreference.com/w/cpp/numeric/math/div

Can you expound on what you are trying to do? Clearly, there's repetitive division intended, but that's all I surmise.

output is a div_t . x is an int , so output = x is like trying to assign an apple to an orange. You can't do it without establishing a set of rules for turning the apple into an orange.

We could try to write such a rule, but why bother? Instead let's look at the code that got us into this predicament and try to figure out the context.

while (x > 0);
{
    div_t output;
    output = x;
    x = div(output, 10);
    kol += kol;
}

The purpose of this loop seems to be to count of the number of times x was divided by ten and store the count in kol .

div_t is the result of a call to div , so assigning a value to the result before performing the operation that will generate the result is a touch unusual. Perhaps OP meant

while (x > 0);
{
    div_t output;
    output = div(x, 10);
    kol += kol;
}

to divide x by ten and get the quotient and remainder.

But this loop will never exit because x is never changed. If it is not zero, the loop will never terminate and if it is zero the loop will never enter. Perhaps

while (x > 0);
{
    div_t output;
    output = div(x, 10);
    x = output.quot;
    kol += kol;
}

would be more appropriate. The remainder is never used however, so div is effectively wasted and

while (x > 0);
{
    x = x / 10; // or x /= 10;
    kol += kol;
}

would provide the same result with far less fuss.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM