c++ - 解释 C++ 中声明性谬误的最佳方法?

标签 c++ declarative procedural

对于为什么以下代码不正确,因为作者试图以声明方式而不是过程方式编写 C++ 代码,人们如何才能做出一个好的解释?

const double NEWTONS_PER_POUND = 4.448;

int main()
{
   double pounds, newtons;
   pounds = newtons/NEWTONS_PER_POUND; /* pounds equals 'unassigned variable'/4.448 */
   newtons = 10.0;
   cout << pounds << endl;             /* a big number, not 10.0/4.448 */
   return 0;
}

作者期望 cout 显示正确的计算结果,但却得到了一个“疯狂的数字”。

我会解释为“C++ 是过程性的,因此在声明时”

pounds = newtons/NEWTONS_PER_POUND;

newtons 尚未被赋值。

有更好的建议吗?或者解释为什么 C++ 不够“智能”以执行用户错误期望的行为?

最佳答案

告诉作者

pounds = newtons/NEWTONS_PER_POUND;

命令CPU

  • 在称为“newtons”的地址处取值
  • 取名为“NEWTONS_PER_POUND”的地址的值
  • 分开他们
  • 将结果存储在称为“磅”的地址

他正在寻找的很可能是一个命令式的函数:

double newtons_to_pounds(double newtons) {
  return newtons/NEWTONS_PER_POUND;
}

...

newtons = 10.0;
cout << newtons_to_pounds(newtons) << endl;    /* a big number, not 10.0/4.448 */
return 0;

关于c++ - 解释 C++ 中声明性谬误的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1360880/

相关文章:

Jenkins 声明式管道 : What workspace is associated with a stage when the agent is set only for the pipeline?

c++ - 计算派生类的最大大小

c++ - 如何防止 r 值

c++ - 使用 GCC 和 GDB 的 Ubuntu 上的 QT Creator - 调试 C++ - 更详细的段错误消息

python - 来自连接的 SQLAlchemy 声明属性(单个属性,而不是整个对象)

javascript - 如何在 Javascript 中以程序化的方式运行一个又一个语句?

c++ - 如果 compile-time-constant 参数错误,则生成编译时错误

haskell - 为什么 Haskell 是完全声明式的?

带有命名空间与 oop 的 php 过程

c++ - 在一行中初始化 pointer(new uint8_t[height * width*3])