【问题标题】:Two digit division from string字符串的两位数除法
【发布时间】:2015-10-22 12:11:13
【问题描述】:

我想定义一个我得到的字符串值。可以说我有一组客户。每个客户在一封信中都设置了多张纸。我有两个字符串变量:

sheetsPerCustomer 和 totalPagescustomer

目前看起来是这样的:

Customer A:
sheetsPerCustomer = "01"  totalPagescustomer "06" // page 1 of 3
sheetsPerCustomer = "02"  totalPagescustomer "06" // page 2 of 3
sheetsPerCustomer = "03"  totalPagescustomer "06" // page 3 of 3

我必须划分 totalPagescustomer,因为总页数是 3 而不是 6。它应该如下所示:

sheetsPerCustomer = "01"  totalPagescustomer "03" // page 1 of 3
sheetsPerCustomer = "02"  totalPagescustomer "03" // page 2 of 3
sheetsPerCustomer = "03"  totalPagescustomer "03" // page 3 of 3

直接除法不起作用,因为如果我将字符串转换为 int 进行除法,“0”将丢失。我需要保留左侧数字,因为总页数可以是 10、20 等,所以我需要两位数。有办法存档吗?

【问题讨论】:

  • 问题不清楚 - 你能给出具体的例子来说明你想要从上面的例子中得到什么结果吗?
  • 对不起。更新了帖子。
  • 所以您只想在每种情况下将totalPagescustomer 除以 2,是吗?但是您想将结果保留为 2 位数字吗?所以06变成0310变成0520变成10

标签: c++ division


【解决方案1】:

省去麻烦并使用整数。它使您的意图更加清晰。如果您尝试使用“类似” int 的东西,那么也许您应该使用 int。

如果您需要显示一个 2 位数字,您可以执行以下操作:

std::cout << std::setfill('0') << std::setw(2) << sheetsPerCustomer  << std::endl;

【讨论】:

    【解决方案2】:

    这是一个类似的方法:

    #include <iostream>
    
    using namespace std;
    
    int main()
    {
       char buf[16];
       int j = 7;
       sprintf(buf, "%02d", j);
       cout << "Result is " << buf << endl;
       return 0;
    }
    

    这打印Result is 07

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-12
      • 1970-01-01
      • 1970-01-01
      • 2011-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-22
      相关资源
      最近更新 更多