C#求完全数,输出水仙花以及类的使用
【摘要】 完全数如果一个正整数等于除它本身之外其他所有除数之和,就称之为完全数。完全数for(int i = 1; i < 1000; i++){int sum = 0;for(int j = 1; j < i; j++){if (i % j == 0){sum += j;}}if (sum == i){Console.WriteLine(i);} 代码using System;using Syst...
完全数
如果一个正整数等于除它本身之外其他所有除数之和,就称之为完全数。
完全数
for(int i = 1; i < 1000; i++)
{
int sum = 0;
for(int j = 1; j < i; j++)
{
if (i % j == 0)
{
sum += j;
}
}
if (sum == i)
{
Console.WriteLine(i);
}
代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
for(int i = 1; i < 1000; i++)
{
int sum = 0;
for(int j = 1; j < i; j++)
{
if (i % j == 0)
{
sum += j;
}
}
if (sum == i)
{
Console.WriteLine(i);
}
}
Console.ReadKey();
}
}
}
结果
以前以内的完全数 6 28 496
输出所有水仙花数
水仙花数是三位数的数,其各位数字的立方和等于该数的本身
水仙花
int a, b, c;
for(int i = 100; i < 1000; i++)
{
a = i / 100;
b = i / 10 %10;
c = i % 10;
if (a * a * a + b * b * b + c * c * c == i)
{
Console.WriteLine(i);
}
代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
int a, b, c;
for(int i = 100; i < 1000; i++)
{
a = i / 100;
b = i / 10 %10;
c = i % 10;
if (a * a * a + b * b * b + c * c * c == i)
{
Console.WriteLine(i);
}
}
Console.ReadKey();
}
}
}
结果
水仙花数为 153 370 371 407
类的使用
代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp6
{
class Student
{
public string name;
public string sex;
public int age;
public Student(string name, string sex)
{
}
public Student(string name, string sex,int age)
{
this.name = name;
this.sex = sex;
this.age = age;
}
public void Inderduce()
{
Console.WriteLine("我叫"+this.name+"我是一个"+this.sex+"孩,我今年"+this.age+"岁");
}
}
class Program
{
static void Main(string[] args)
{
Student s1 = new Student("小华","男",20);
Student s2 = new Student("小花","女",18);
s1.Inderduce();
s2.Inderduce();
Console.ReadKey();
}
}
}
输出结果
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)