如何在一系列整数中除以a? [英] how to divide a number a in a series of all whole numbers?

查看:104
本文介绍了如何在一系列整数中除以a?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,问这是否是一个愚蠢的问题.

Hi sorry for asking this if this is a stupid question.

我想问一下如何在Javascript中安全地除以一个数字,该数字将始终 以将结果输出为纯整数的方式输出结果.

I would like to ask how to securely divide a number in Javascript that it will always output the result in a way that it will output pure whole numbers.

示例:

10/2 ---> 5、5(这是2个5,所以它是整数)

10 / 2 ---> 5, 5 ( it would be 2 fives so it is whole number )

但是

10/3 ---> 3、3、4(它会有两个3和一个4,因此仍然会得到10)

10 / 3 ---> 3, 3, 4 ( it would have two 3 and one 4 so that it would still result to 10 )

推荐答案

10/3将给您3.333333 ...,从不给您四个...如果您要检查的是一个数字,您将得到全部数字"例如,使用模(%).

10/3 will give you 3.333333..., never four... if you want to check is a number will give you "whole numbers" as you say, use modulo (%).

Modulo求出一个数除以另一数的余数.

Modulo finds the remainder of division of one number by another.

例如

10%5 = 0,因为10除以5是整数"

10%5 = 0 because 10 divided by 5 is a "whole number"

10%3 = 1,因为最接近的10/3是3 ... 3x3 = 9 ... 10-9 = 1

10%3 = 1 because the closest 10/3 is 3... 3x3=9... 10-9=1

因此,在您的代码中,如果您想知道一个数字除以另一个数字是否是整数,则需要这样做

So in your code, if you want to know if a number divided by another number is whole, you need to do

if (number1%number2 == 0) { ... }

详细了解此处

我再次阅读了您的问题,我认为这把小提琴就是您想要的

I read your question again and I think this fiddle is what you want

var number1 = 10,
    number2 = 3;

if (number1 / number2 == 0) {
    alert('the numbers are whole');
} else {
    var remainder = number1%number2;
    var wholes = Math.floor(number1 / number2);

    var output = '';

    for (var i = 0; i < (wholes - 1); i++) {
     output+= number2 + ', ';
    }

    output += (number2 + remainder);

    alert(output);
}

这篇关于如何在一系列整数中除以a?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆