[英]C#: Wrong answer when finding “cool” numbers
在我的應用程序中,“酷”數字是既是正方形又是立方體的數字,例如:64 = 8 ^ 2和64 = 4 ^ 3。 我的應用程序應該在用戶給定的范圍內找到“冷靜數字”的數量。 我寫了代碼,應用程序運行正常,但是給了我錯誤的答案。 你能幫我嗎? 例如:
輸入
1100
輸出值
1個
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
double a = Convert.ToDouble(Console.ReadLine()); // first number in the range
double b = Convert.ToDouble(Console.ReadLine()); // second number in the range
long x = 0;
for (double i = a; i <= b; i++)
{
double cube = 1.0 / 3.0;
double cuad = 1.0 / 2.0;
double crt = Math.Pow(i, cube); // cube root
double sqrt = Math.Pow(i, cuad); // square root
if ((crt * 10) % 10 == 0 || (sqrt * 10) % 10 == 0) // condition to determine if it is a cool number.
x++;
}
Console.WriteLine(x);
Console.ReadLine();
}
}
}
“酷數字”是描述第六種力量的一種s回的方式。 顯然,每六次方是一個很酷的數字; x ^ 6是(x ^ 2)^ 3和(x ^ 3)^ 2。 每個不是六次冪的數字也不是一個很酷的數字。 (證明是一種練習。提示:請考慮任何一個很酷的質數分解的必要性質。)
因此,我將簡單地編寫一個枚舉范圍內的第六次冪的設備。
在大多數語言中, double
都是凌亂的。 它們通常存儲不准確,有時會給您錯誤的答案。 您不想在不需要時使用它們。
這就是我要做的。 從用戶那里取兩個int
。 循環遍歷這兩個int
范圍內的整數(就像使用浮點數一樣。)對於每個整數,找到立方根和平方根並將它們存儲為雙精度。 然后將立方根和平方根四舍五入為最接近的整數(使用庫函數)並將其存儲為int
。 最后,要查看當前數字是平方還是立方,請將平方根int
乘以自身,並將立方根int
乘以本身,然后查看這兩個乘積是否等於原始數。 如果他們這樣做,您將獲得一個不錯的號碼。
這樣,舍入功能可以確保篩選出雙精度中的所有精度錯誤,然后所有數字都很好聽而且很健康。
一些代碼:
int a = int_from_user();
int b = int_from_user();
for (i = a; i <= b; i++) {
int sqrt = round(sqrt(i));
int cbrt = round(cbrt(i));
if (sqrt * sqrt == i && cbrt * cbrt * cbrt == i) {
cool++;
}
}
|| 如果其中一個部分為真,則算符應為true,因此,如果((crt * 10)%10 == 0 &&(sqrt * 10)%10 = = 0)
這是另一個選擇,有點慢,但是您可以對其進行測試:
if (((crt == Math.Floor(crt)) && (sqrt == Math.Floor(sqrt))) x++;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.