标签: while-loop

JavaScript。while 循环无法识别全局变量

我在 codecadamy.com 上的 Javascript 教程午餐时间。

我有这个简单的循环:

var cards = ['Diamond', 'Spade', 'Heart', 'Club'];
var currentCard = 'Heart';

while (currentCard !== 'Spade') {
  console.log(currentCard);

  var randomNumber = Math.floor(Math.random() * 4);

  currentCard = cards[randomNumber];
}

console.log('Found a Spade!');
Run Code Online (Sandbox Code Playgroud)

这很好,但是如果我randomNumber从循环中删除并与其他全局变量一起放置,codecademy 控制台不会打印结果......

由于全局变量应该可用于该循环,我认为 codecademy 控制台有问题?

你同意这应该有效吗?

var cards = ['Diamond', 'Spade', 'Heart', 'Club'];
var currentCard = 'Heart';
var randomNumber = Math.floor(Math.random() * 4);

while (currentCard !== 'Spade') {
  console.log(currentCard);
  currentCard = cards[randomNumber];
}

console.log('Found a Spade!');
Run Code Online (Sandbox Code Playgroud)

javascript global-variables while-loop

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

如何在 C++ 中执行 60 秒的 while 循环?

有谁知道如何运行这个循环 60 秒然后停止?这是我的代码:

#include<iostream.h>
#include<conio.h>
int main()
{
    clrscr();
    int a=1;
    int b;
    cout<<"3.";
    b=a*10%7;
    while(b!=0)
    {
        cout<<a/7;
        a=b*10;
        b=a%7;
    }
    getch();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c++ while-loop

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

在具有最大整数重复项的数组中查找第二个最大值

我试图找到数字数组中的第二大数字,但最大的数字出现两次,所以我不能只是将其从数组中删除并选择新的最大数字。

array = [0, 3, 2, 5, 5](因此3是第二大值)

我有这段代码,可以显式返回 3,但它不适用于其他数组:

    function getSecondLargest(nums) {

      var sorted_array = nums.sort(function (a,b) {return a - b;});
      var unique_sorted_array = sorted_array.filter(function(elem, index, self) {
    return index === self.indexOf(elem);
})

    return unique_sorted_array[unique_sorted_array.length - 2];
}

return unique_sorted_array[unique_sorted_array.length - 2];
Run Code Online (Sandbox Code Playgroud)

如果我想让它更加动态,有没有一种方法可以识别数组的最大值,然后将其与数组的每次迭代进行比较?

我在想类似的事情:

var greatestNum = sortedArray[-1]

while(greatestNum != i) do {
  //check for the first number that doesn't equal greatestNum
}
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激。

javascript arrays while-loop

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

如何用C语言画帕斯卡三角形?

我正在尝试编写打印以下内容的代码:

帕斯卡三角

这是我尝试过的:

#include <stdio.h>

int main() {
    int i, j, rows;

    printf("Enter number of rows: ");
    scanf("%d", &rows);

    for (i = rows; i >= 0; i--) {

        for (j = 1; j <= i; ++j) {
            printf("* ");
        }

        printf("\n");
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢 ?

c loops for-loop while-loop

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

如何提前退出 while 循环

假设我有一个无限while循环并且我想退出循环。这样做的正确方法是什么?OCaml 没有break,因此我可能必须引发异常来终止循环 ( try while true do ... raise My_exception ... done with My_exception -> ())。这是退出无限循环的惯用方法吗?我应该在循环内引发哪个异常?

ocaml while-loop

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

if、else 和 elif 的问题

我是 python 新手,目前在我的代码中遇到了障碍。我知道这可能太明显而难以注意到,但我无法理解它。我目前正在尝试编写一段代码来询问一堆问题并让用户知道在大流行期间该做什么,并且只接受用户输入 y 或 n,如果用户输入其他任何内容,代码将询问用户再次输入

yesChoice=["y", "Y"]
noChoice=["n", "N"]
while True:
    HRW=input("Did you receive a Health Risk Warning(HRW) Notice (y/n)?: ")
    if HRW==yesChoice:
        print("Follow protocol of 3-5 days of monitoring, test ART within 24 hrs")
    elif HRW==noChoice:
        well=input("Are you feeling well (y/n)?: ")
        if well==noChoice:
            print("Visit a doctor to assess on the next step")
        else:
            print("For safety measures, please do an ART test")
    else:
        print("Please enter y/n")
        continue
Run Code Online (Sandbox Code Playgroud)

我将在代码中添加更多内容以进行进一步的步骤,但目前当我输入 y 时,它只会继续打印“请输入 y/n”并继续询问“您是否收到健康风险警告(HRW)通知(是/否)”。这里到底是什么问题?提前致谢!

python if-statement while-loop

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

Rust:“while true”无法编译,但“loop”可以

我对 Rust 和一般的低级语言都很陌生。我注意到在下面的代码中,如果我替换loop为while true代码将不再编译。我实际上希望该版本loop也不会编译,因为 return 语句位于 if 语句内,因此并非所有代码路径都会返回值。

pub fn two_sum(numbers: Vec<i32>, target: i32) -> Vec<i32> {
    let mut left = 0;
    let mut right = numbers.len() - 1;
    loop {
        while numbers[left] + numbers[right] > target { 
            right -= 1;
        }
        if numbers[left] + numbers[right] == target {
            break vec![left as i32 + 1, right as i32 + 1];
        } else { 
            left += 1;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我也愿意接受有关如何使上面的代码更符合 Rust 习惯的建议!

loops while-loop rust

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

连接具有公共点的线

我有一个这样的行列表:

Lines = ['1', '2', '3', '4', '5', '6', '7', '8']
Run Code Online (Sandbox Code Playgroud)

每条线有两个点 I 和 J:

LinesDetail = {
    '1': {
        'I': '100',
        'J': '101'},
    '2': {
        'I': '101',
        'J': '102'},
    '3': {
        'I': '256',
        'J': '257'},
    '4': {
        'I': '257',
        'J': '258'},
    '5': {
        'I': '258',
        'J': '259'},
    '6': {
        'I': '304',
        'J': '305'},
    '7': {
        'I': '305',
        'J': '306'},
    '8': {
        'I': '102',
        'J': '103'}}
Run Code Online (Sandbox Code Playgroud)

正如您在图片中看到的,其中一些线具有相互点,因此它们相互连接,我需要知道哪些线相互连接。

我尝试了 while 循环,但我不知道如何解决此类问题的基本概念。

线路

结果是:

result = [["1","2","8"],["3","4","5"],["6","7"]]
Run Code Online (Sandbox Code Playgroud)

所有线都是垂直的

python algorithm plot graph-theory while-loop

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

while 陷入 def 函数中

我的任务如下:

给定三个整数。确定其中有多少个彼此相等。程序必须打印以下数字之一:3(如果所有数字都相同)、2(如果其中两个相同且第三个不同)或 0(如果所有数字都不同)。

我想我可以做一个 def 函数来检查输入是否都是整数而不是浮点数或字符串。虽然程序在仅输入整数的情况下可以工作,但它会卡在 my 上,除非输入另一种类型

def valuecheck(checker):
  loopx = True
  while loopx:
    try:
      #first it checks if the input is actually an integer
      checker = int(checker)
      loopx = False 
      return(checker)
      #if input isn't an integer the below prompt is printed
    except:
     input("Value isn't a valid input, try again: ")

varA = input("please input an integer: ")
varA = valuecheck(varA)
x = varA

varB = input("please input anther integer: ")
varB = valuecheck(varB)
y = varB

varC = …
Run Code Online (Sandbox Code Playgroud)

python while-loop

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

C# 中的 While 循环

我想当 和 都i具有j值 6 时退出循环,但当其中一个具有值 时它退出6。

int i,j,k;
i=k=0;
j=1;
Random num = new Random();
Console.WriteLine("Please Press any Key to Roll");
while((i!=6)&&(j!=6))
{
    Console.ReadKey();
    i= num.Next(0,7);
    j= num.Next(0,7);
    Console.WriteLine("1st Rolled Number is: "+ i);
    Console.WriteLine("2st Rolled Number is: "+ j);
    k++;
}
Console.WriteLine("Your have achieved it in "+ k + " Atempts");
Run Code Online (Sandbox Code Playgroud)

c# console-application while-loop

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