将Python算法转换为C#。问题在于 [英] Converting a Python algorithm to C#. The problem lies
问题描述
这是C#代码。我的问题是它打印七个1和一个2,当它应该按顺序打印vals列表。 (如排序)。
使用System;
使用System.Collections.Generic;
命名空间ConsoleApp5
{
class程序
{
static void Main()
{
int [] vals = { 6,5,3,1,8,7,2,4};
// List< int> vals = new List< int> {6,5,3,1,8,7,2,4};
int n = 8;
for(int i = 0; i< n; i ++)//< =或<?
{
for(int j = 0; j< n - 1; j + = 1)
{
if(vals [j]> vals [j + 1])$ b $ b {
vals [j] = vals [j + 1];
vals [j + 1] = vals [j];
}
}
}
foreach(int num in vals)
{
Console.WriteLine(vals [num ]);
}
}
}
}
这是python代码:
vals = [6,5,3,1,8 ,7,2,4]
n = len(vals)
for i in range(n):
for j in range(0,n-1):
如果vals [j]> vals [j + 1]:
vals [j],vals [j + 1] = vals [j + 1],vals [j]
print(vals)
我的尝试:
我是尝试将它从一个数组改为一个列表,反之亦然,没有改变任何东西。
我已经尝试了很多关于循环的东西,目前它们按预期工作。
谢谢。
if (vals [j] > vals [j + 1 ] )
{
vals [j] = vals [j + 1 ];
vals [j + 1 ] = vals [j];
}
您无法像这样交换两个单元格。将vals [j]
设置为vals [j + 1]
的值,然后设置vals [j + 1]
到vals [j]
的值,这已经是的先前值vals [j + 1]
。你需要将第一项复制到这样的临时变量:
if (vals [j] > vals [j + 1 ])
{
int temp = vals [j]; // 保存原始值
vals [j] = vals [j + 1 跨度>];
vals [j + 1 ] = temp; // vals中的原始值[j]
}
This is the C# code. My problem is that it prints seven 1s and a 2, when it is supposed to print the vals list in order. (like a Sort).
using System; using System.Collections.Generic; namespace ConsoleApp5 { class Program { static void Main() { int[] vals = {6, 5, 3, 1, 8, 7, 2, 4}; //List<int> vals = new List<int> { 6, 5, 3, 1, 8, 7, 2, 4 }; int n = 8; for (int i = 0; i < n; i++)//<= or <? { for (int j = 0; j < n - 1; j += 1 ) { if (vals[j] > vals[j + 1]) { vals[j] = vals[j + 1]; vals[j + 1] = vals[j]; } } } foreach (int num in vals) { Console.WriteLine(vals[num]); } } } }
and this is the python code:
vals = [6,5,3,1,8,7,2,4] n = len(vals) for i in range(n): for j in range(0, n-1): if vals[j] > vals[j+1]: vals[j], vals[j+1] = vals[j+1], vals[j] print(vals)
What I have tried:
I've tries changing it from an array to a list and vise versa, didn't change anything.
I've tried a lot of things with the loops, at present they work as intended.
Thank you.
if (vals[j] > vals[j + 1]) { vals[j] = vals[j + 1]; vals[j + 1] = vals[j]; }
You cannot exchange two cells like that. You setvals[j]
to the value ofvals[j + 1]
, and then setvals[j + 1]
to the value ofvals[j]
, which is already the previous value ofvals[j + 1]
. You need to copy the first item to a temporary variable like this:
if (vals[j] > vals[j + 1]) { int temp = vals[j]; // save original value vals[j] = vals[j + 1]; vals[j + 1] = temp; // original value in vals[j] }
这篇关于将Python算法转换为C#。问题在于的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!