对于为什么以下代码不正确,因为作者试图以声明方式而不是过程方式编写 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/