这是Ruby中的Pig Latin translate practice。
为什么我从这两个版本的代码中得到不同的结果?换句话说,为什么theme
没有在第二个代码块中生效?
#include "stdafx.h"
#include<iostream>
#include<conio.h>
using namespace std;
class rez {
float r;
public:
void set(int n);
float val() { return r; }
};
void rez :: set(int n) { //n is the number of resistances
int i;
for (i = 1; i <= n; i++) {
cout << "R" << i << "=";
cin >> r;
}
}
float serie(rez r1,int n)
{
float s=0;
int i;
for (i = 1; i <= n; i++)
{
s = s+ r1.val();
}
return s;
}
float para(rez r1, int n)
{
float s = 0;
int i;
for (i = 1; i <= n; i++)
{
s = s + (1/r1.val());
}
return 1/s;
}
int main()
{
char c, k = 'y'; // 'c' selects series or para
rez r1;
int n;
cout << "number of resis:";
cin >> n;
cout << endl;
while (k != 'q')
{
r1.set(n);
float i, u;
cout << "\n Vdc= ";
cin >> u;
cout << endl;
cout << "series or para(s/p)?"<<endl;
cin >> c;
switch (c)
{
case('s'):cout <<"\n equiv resistance = "<< serie(r1,n)<<endl;
i = u / serie(r1, n);
cout << "curr i = " << i << " amp";
break;
case('p'):cout << "\n equiv res = " << para(r1, n)<<endl;
i = u / para(r1, n);
cout << "cur i = " << i << " amp";
break;
}
cout <<endl<< "\n another set?(y/q)?"<<endl;
cin >> k;
}
return 0;
}
输出:
word = word[i..-1]
和
def translate(input)
output_array = input.split(" ").each do |word|
i=0
while !['a', 'e', 'i', 'o', 'u'].include?(word[i])
i += 1
end
unless i == 0
word << word[0..i-1]
word[0..i-1] = ''
end
word << "ay"
end
return output_array.join(" ")
end
puts translate('apple')
puts translate('banana')
puts translate('trash')
puts translate('eat pie')
打印出来:
appleay
ananabay
ashtray
eatay iepay
答案 0 :(得分:0)
output_array = input.split(" ").each do |word|
i=0
while !['a', 'e', 'i', 'o', 'u'].include?(word[i])
i += 1
end
unless i == 0
word << word[0..i-1] # Good
word = word[i..-1] # Bad
end
word << "ay"
end
该行
word << word[0..i-1]
更改字符串,而
word = word[i..-1]
创建一个新字符串并将新字符串分配给word
。更改新字符串不会影响数组中的旧字符串,因此数组中的单词保持在
word << word[0..i-1]
进行每次修改(就像你在解决方案1中所做的那样),或者使用更像Ruby的Array#map
。
这是偏离主题的,但您的while
循环可以替换为
i = word.index(/[aeiou]/)
如果你碰巧知道正则表达式。