【问题标题】:what is wrong with this c++ code to find the sum of all multiples of 5 and 3 below 1000? [closed]这段 C++ 代码在 1000 以下找到所有 5 和 3 的倍数之和有什么问题? [关闭]
【发布时间】:2016-11-11 20:41:05
【问题描述】:

我很中级。我知道有更快的方法来解决这个 Project Euler 问题,但这是我想出的方法,它应该仍然有效,对吧?我知道这个问题不是很具体,但我发现很难用谷歌搜索一个我不知道的问题。任何帮助表示赞赏:(

#include <iostream>
#include <math.h>                           //declare floor
using namespace std;


int main()
{
    cout << "What number would you like to find the sum of all multiples of 5 and 3?"<<endl;
    int n;
    int sum = 0;
    cin >> n;
    for(int x = 1; x < n; x = x + 1){
           float f = x/5;                   //divides every number from 0 to n-1 (intended to be 1000) by 5.
           float t = x/3;
           if(floor(f) == f){               //checks to see if it is a whole number by rounding the answer, and seeing if that equals the original. If it does, it is truly a whole number answer.
                sum = sum + x;              //since it is divisible by 5, the number is added to the sum.
           }else{                           //this is ELSE so that same multiples aren't counted twice. if x is not multiple of 5, check to see if it's a multiple of 3. if none, nothing happens
                 if (floor(t) == t){
                    sum = sum + x;
                }
           }
    }
    cout << "Sum of all multiples is " << sum << endl;
    return 0;
}

【问题讨论】:

  • 对于这个问题不要使用浮点数(或双精度)。
  • 正如@RichardCritten 所说,您不需要使用这些数据类型。我建议使用% 运算符。
  • 其实这最好描述为初级问题
  • 一个非常初级的问题。

标签: c++ if-statement for-loop floor


【解决方案1】:

x5 在以下语句中都是整数。

float f = x/5; 

所以结果总是等于除法的商。

您应该将代码更改为以下内容:

float f = x/5.f; 

如果你想得到一个浮动结果。

但是,这不会解决您的问题,可以像下面这样更容易解决:

for(int x = 1; x < n; x = x + 1){
    if(x%5== 0 || x%3 == 0){
        sum = sum + x;
    }
}

% 是取模运算符,为您提供两个整数之间除法的余数。如需更多信息,请查看here

【讨论】:

  • ...所以调用浮点除法而不是整数除法
  • 谢谢!这正是我所需要的!
  • @NJLStudios1 欢迎您。我很高兴能帮上忙:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多