简体   繁体   English

我不明白的 C++ 错误

[英]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)我得到了这个错误:错误 1 ​​错误 C2679: 二进制 '=' : no operator found which requires a right-hand operation of 'int' (or there is no Acceptable talk)

Can someone tell me what I did wrong, and how to fix?有人可以告诉我我做错了什么,以及如何解决?

You are treating div_t like an int;您将 div_t 视为 int; it isn't one.它不是一个。 It's a struct.这是一个结构。

See http://en.cppreference.com/w/cpp/numeric/math/div请参阅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 . output是一个div_t x is an int , so output = x is like trying to assign an apple to an orange. x是一个int ,所以output = x就像试图将一个苹果分配给一个橙子。 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 .这个循环的目的似乎是计算x除以 10 的次数并将计数存储在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. div_t是调用div的结果,因此在执行将生成结果的操作之前为结果分配一个值是一种不寻常的触摸。 Perhaps OP meant也许 OP 的意思是

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

to divide x by ten and get the quotient and remainder.x除以 10 并得到商和余数。

But this loop will never exit because x is never changed.但是这个循环永远不会退出,因为x永远不会改变。 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然而,余数从未使用过,因此div被有效地浪费了,并且

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

would provide the same result with far less fuss.会以更少的麻烦提供相同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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