大家好,我有一个简单的问题.所以我有一个任务,我必须创建一个程序,递归计算整数中所有数字的总和.IE整数123(1 + 2 + 3)= 6.如何从第一个数字开始并继续运行直到没有其他数字?这就是我到目前为止......
import java.util.*;
public class sum
{
/**
* @param args
*/
public static void main(String[] args)
{
System.out.println(sumDigits(123))
}
public static int sumDigits(int n)
{
while (n.hasNext())
{
return n.charAt(n.length) + sumDigits(n.charAt((n.length - 1)))
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在我知道我正在使用(hasNext和charAt,我不应该......)但是int的等价物是什么?
大家好,我有一些东西,我的大脑很难弄清楚.我的作业是拥有"x"兔子.它递归地计算兔子耳朵的总数.偶数兔子有正常的两只耳朵,奇数兔子有3只耳朵,但每5只兔子有1只耳朵.我的代码完整而且有效...这里是......
import java.util.*;
public class bunnies
{
public static int y;
public static void main(String[] args)
{
y = 0;
System.out.println(BunnyEars(3));
}
public static int BunnyEars(int x)
{
if ((x % 5) == 0 && x != 1 && x != 0)
return 1 + BunnyEars(x - 1);
else if ((x % 2) == 0 && x != 0 )
return 2 + BunnyEars(x - 1);
else if ((x % 2) != 0 && x != 0)
return 3 + …Run Code Online (Sandbox Code Playgroud) 我正在创建一个编辑距离程序,它接收两个字符串指针并返回它们之间的编辑距离.我遇到的唯一问题是结束该计划.基本上当用户为两个字符串输入-1时,程序应该结束.我一直在尝试所有类型的东西和搜索,但似乎无法阻止它.这就是我所拥有的:
char * word1;
char * word2;
char string1[1000];
char string2[1000];
int d;
do{
printf("Enter first string:");
scanf("%s", &string1);
printf("Enter second string:");
scanf("%s", &string2);
if((int)string1[0] == -1 && (int)string2[0] == -1)
break;
printf("%d\n", string1[0]);
word1 = string1;
word2 = string2;
printf("%s\n", word1);
printf("%s\n", word2);
d = distance (word1, word2);
printf ("The edit distance between %s and %s is %d.\n",word1, word2, d);
}while((int)string1[0] != -1);
return 0;
Run Code Online (Sandbox Code Playgroud) 嘿家伙所以我有一个文本文件,我试图从中读取并接收每个数字字符串并将其转换为浮点数.但是每当我尝试它时,它都会说"把绳子转换成浮子".为什么会这样?谢谢!
try:
input_file = open("Dic9812.TFITF.encoded.txt","r")
output_fileDec = open("Dic9812.TFITF.decoded.txt","w")
output_fileLog = open("Dic9812.TFITF.log.txt","w")
except IOError:
print("File not found!")
coefficientInt = input("Enter a coefficient: ")
coefficientFl = float(coefficientInt)
constInt = input("Enter a constant: ")
constFl = float(constInt)
try:
for line in input_file:
for numstr in line.split(","):
numFl = float(numstr)
print(numFl)
except Exception as e:
print(e)
Run Code Online (Sandbox Code Playgroud)
该文件如下所示:
135.0,201.0,301.0
152.0,253.0,36.0,52.0
53.0,25.0,369.0,25.0
Run Code Online (Sandbox Code Playgroud)
它最终打印数字,但最后它说:不能将字符串转换为浮点数:
您好我有一个问题,我必须打印出可被17整除的数字,但我想打印5个数字,然后跳到下一行.这是我的代码,不知道为什么它不起作用....
public class seventeen {
public static void main(String[] args) {
int num = 17;
System.out.print("The Numbers Divisible By 17 are: ");
int enter = 0;
for (int x = 1; x <= 10000; x++) {
if (x % num == 0) {
System.out.print(x + " ");
}
enter++;
if (enter == 5) {
enter = 0;
System.out.println();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)