我對編程很陌生,我在嘗試撰寫一個程式時遇到了困難,在該程式中,您輸入產品的名稱和價格,然后回傳總數、名稱 價格和最昂貴的產品。除了顯示最昂貴產品的名稱外,一切正常。這是我所做的
“”
Public Class Mrj
Shared Sub main()
Dim i, n As Integer
Console.WriteLine("Enter the number of products")
n = Console.ReadLine()
Dim Products_name(n) As String
Dim Products_price(n), HT, TTC, TVA, max As Decimal
For i = 1 To n
Console.WriteLine("Enter the name of the product " & i)
Products_name(i - 1) = Console.ReadLine()
Console.WriteLine("Enter the price of the product " & i)
Products_price(i - 1) = Console.ReadLine()
HT = HT Products_price(i - 1)
Next
For i = 1 To n
Console.WriteLine(Products_name(i - 1) & " " & Products_price(i - 1))
Next
TVA = 0.2 * HT
TTC = HT TVA
Console.WriteLine("Total to pay " & TTC)
max = Products_price(0)
For i = 1 To n - 1
If max > Products_price(i) Then
Else
max = Products_price(i)
End If
Next
Console.WriteLine("The product the most expensive is" & max & Products_name(i))
End Sub
End Class
“”
uj5u.com熱心網友回復:
我認為問題在于您使用的i是獲取最昂貴產品的名稱,但該索引i始終存在,i = n因為您沒有保存最大值的索引。
您應該在每次獲得新的最大值時添加一個新變數來存盤索引,并在最后一行中使用它。
你的for回圈應該是這樣的:
Dim max_index As Integer
For i = 1 To n - 1
If max > Products_price(i) Then
Else
max = Products_price(i)
max_index = i
End If
Next
Console.WriteLine("The product the most expensive is" & max & Products_name(max_index))
試試這個并檢查它是否有效。
uj5u.com熱心網友回復:
現在和永遠打開 Option Strict。專案屬性 -> 編譯選項卡。也適用于未來的專案工具 -> 選項 -> 專案和解決方案 -> VB 默認值
您不能假設用戶實際上會輸入一個數字。用 測驗TryParse。
vb.net 中的陣列被宣告Products_name(upper bound)。在這種情況下,這將是Products_name(n-1)
而不是為回圈中i - 1的索引做For,開始我們的For i = 0 to n-1
我決定不使用并行陣列。相反,我創建了一個小類并宣告了一個List(Of Product). 我用用戶輸入設定Properties了Product.
我使用 Linq 而不是回圈來求和和最大值。不一定更快,但可以在一行代碼中完成。
我使用內插字串來顯示結果。當您的字串前面有 a 時$,您可以直接在大括號括起來的文本中插入變數。后面的冒號Price表示格式化字符。在這里,我使用了C貨幣。
公共類產品公共屬性名稱作為字串公共屬性價格作為十進制結束類
Sub main()
Dim ProductList As New List(Of Product)
Dim n As Integer
Console.WriteLine("Enter the number of products")
Integer.TryParse(Console.ReadLine, n)
For i = 1 To n
Dim p As New Product
Dim pr As Decimal
Console.WriteLine("Enter the name of the product " & i)
p.Name = Console.ReadLine()
Console.WriteLine("Enter the price of the product " & i)
Decimal.TryParse(Console.ReadLine, pr)
p.Price = pr
ProductList.Add(p)
Next
For Each p In ProductList
Console.WriteLine($"{p.Name} {p.Price:C}")
Next
Dim SubTotal As Decimal = ProductList.Sum(Function(item) item.Price)
Dim Tax As Decimal = 0.2D * SubTotal
Dim Total = SubTotal Tax
Console.WriteLine($"Total to pay {Total:C}")
Dim Prod = ProductList.OrderByDescending(Function(p) p.Price).FirstOrDefault()
Console.WriteLine($"The product the most expensive is {Prod.Name} at {Prod.Price:C}")
Console.ReadKey()
End Sub
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/395533.html
標籤:网络
