我正在尝试创建一个函数,该函数接收一个数字作为参数,并对该数字执行操作以找出其最接近2的幂,然后将该数字加起来.例如,如果用户输入4,则该函数将附加4,因为它已经是2的幂.如果用户输入14,则该函数应该看到14不是2的幂,并且最接近2的幂组成14是2,4和8.
主要提示:我只能达到2 ^ 9.
到目前为止我有什么:
def powers_finder(n):
powers=[]
i=0
total=0
while i<10:
value=2**i
total=total+value
i=i+1
#This if statement is for if the user enters a power of 2 as n
#Then the number will be appended right away into my powers list.
if value==n:
powers.append(value)
Run Code Online (Sandbox Code Playgroud)
这里的问题是,如果用户输入,则假设5为(n)5由功率2 ^ 2 = 4和2 ^ 0 = 1 4 + 1 = 5组成.如何扩展我的功能以包含此过程?
谢谢!
有没有办法通过轴的分数在图形中定位文本?无论 x 和 y 的范围如何,我都希望所有绘图的文本都位于相同的位置。此功能在 ax.annotate() 中,但我需要添加额外的 'xy' 参数,这会使我的代码更难阅读。
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(np.arange(10),12*np.arange(10))
ax.annotate('Correct Position', xy=(0, 0), xytext=(0.4, 0.7), textcoords='axes fraction')
ax.text(0.4, 0.7, 'Incorrect Position')
plt.show()
Run Code Online (Sandbox Code Playgroud) 为什么这个程序输出Generic Value而不是Hello world!:
using System;
class Example
{
public static void Print<T>(T value)
{
Console.WriteLine("Generic Value");
}
public static void Print(string value)
{
Console.WriteLine(value);
}
public static void GenericFunc<T>(T value)
{
Print(value);
}
static void Main()
{
GenericFunc("Hello world!");
}
}
Run Code Online (Sandbox Code Playgroud)
泛型方法参数如何在C#的引擎下翻译?