小编Har*_*ise的帖子

64位数学运算,不会丢失任何数据或精度

我相信128位数据没有任何便携式标准数据类型.因此,我的问题是如何在不使用现有标准数据类型丢失数据的情况下有效地执行64位操作.

例如:我有两个uint64_t类型变量:

uint64_t x = -1; uint64_t y = -1;

现在,如何x+y, x-y, x*y and x/y存储/检索/打印数学运算的结果?

对于上面的变量,x + y得到-1的值,实际上是带有进位1的0xFFFFFFFFFFFFFFFFULL.

void add (uint64_t a, uint64_t b, uint64_t result_high, uint64_t result_low)
{
    result_low = result_high = 0;
    result_low  = a + b;
    result_high += (result_low < a);
}
Run Code Online (Sandbox Code Playgroud)

如何执行其他操作add,从而提供适当的最终输出?

如果有人共享通用算法,我会很感激,这些算法可以处理使用这些操作可能出现的溢出/下溢等.

任何可能有帮助的标准测试算法.

c algorithm math arithmetic-expressions operators

1
推荐指数
1
解决办法
333
查看次数

了解c ++中的模板

我正在尝试运行以下程序,但它会生成编译错误:

#ifndef TEMPLATE_SUM_H_
#define TEMPLATE_SUM_H_

template<typename T>
class sum
{
  public:
    sum() {
      val_1 = 0;
      val_2 = 0;
    }
    sum(T a, T b) {
      val_1 = a;
      val_2 = b;
    }
    friend std::ostream& operator<<(std::ostream &, const sum<> &);

  private:
    T val_1, val_2;
    T result() const;
};

#endif
Run Code Online (Sandbox Code Playgroud)

源文件:

include <iostream>
#include "inc/sum.h"

template<typename T>
T sum<T>::result() const {
   return (val_1 + val_2);
}

template<typename T>
std::ostream& operator<<(std::ostream& os, const sum<T>& obj) {
//std::ostream& operator<<(std::ostream& os, sum<T>& obj) {
  os …
Run Code Online (Sandbox Code Playgroud)

c++ templates

1
推荐指数
1
解决办法
306
查看次数

标签 统计

algorithm ×1

arithmetic-expressions ×1

c ×1

c++ ×1

math ×1

operators ×1

templates ×1