繁体   English   中英

我不明白的 C++ 错误

[英]A C++ error that I don't understand

所以这是我的代码

#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;
}

我得到了这个错误:错误 1 ​​错误 C2679: 二进制 '=' : no operator found which requires a right-hand operation of 'int' (or there is no Acceptable talk)

有人可以告诉我我做错了什么,以及如何解决?

您将 div_t 视为 int; 它不是一个。 这是一个结构。

请参阅http://en.cppreference.com/w/cpp/numeric/math/div

你能解释一下你正在尝试做什么吗? 显然,有重复的划分意图,但这就是我的猜测。

output是一个div_t x是一个int ,所以output = x就像试图将一个苹果分配给一个橙子。 如果没有建立一套将苹果变成橙子的规则,你就无法做到这一点。

我们可以尝试编写这样的规则,但何必呢? 相反,让我们看看让我们陷入这种困境的代码,并尝试找出上下文。

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

这个循环的目的似乎是计算x除以 10 的次数并将计数存储在kol

div_t是调用div的结果,因此在执行将生成结果的操作之前为结果分配一个值是一种不寻常的触摸。 也许 OP 的意思是

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

x除以 10 并得到商和余数。

但是这个循环永远不会退出,因为x永远不会改变。 如果它不为零,循环将永远不会终止,如果它为零,则循环永远不会进入。 也许

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

会更合适。 然而,余数从未使用过,因此div被有效地浪费了,并且

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

会以更少的麻烦提供相同的结果。

暂无
暂无

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

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